using System.Text;
using Microsoft.AspNetCore.Mvc;

namespace NostrServices.Controllers;

[Route("/api/v1/avatar")]
public class AvatarController : Controller
{
    /// <summary>
    /// Robohash avatar endpoints
    /// </summary>
    /// <remarks>
    /// Available sets: `cyberpunks` / `robots` / `zombies`
    /// </remarks>
    /// <param name="set"></param>
    /// <param name="value">Any value, can contain a file extension, response is only image/webp</param>
    /// <returns></returns>
    [HttpGet("{set}/{value}")]
    [ResponseCache(Location = ResponseCacheLocation.Any, Duration = 86400)]
    public IActionResult GetAvatar([FromRoute] string set, [FromRoute] string value)
    {
        var hash = System.Security.Cryptography.SHA256.HashData(
            Encoding.UTF8.GetBytes(Path.GetFileNameWithoutExtension(value)));
        var hashInt = BitConverter.ToInt32(hash);
        var dir = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", set);
        var fileList = Directory.EnumerateFiles(dir, "*.webp").ToList();
        var pickImg = fileList[Math.Abs(hashInt % fileList.Count)];
        return PhysicalFile(pickImg, "image/webp");
    }
}