using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Chat.Domain.Tools
{
    public class Base64ToFormFile
    {
        public static IFormFile ConvertBase64ToFormFile(string base64String, string fileName)
        {
            // Remove o prefixo "data:image/png;base64," se existir
            if (base64String.Contains(","))
            {
                base64String = base64String.Split(',')[1];
            }

            // Converte base64 para bytes
            byte[] bytes = Convert.FromBase64String(base64String);

            // Cria um stream de memória com os bytes
            var stream = new MemoryStream(bytes);

            // Cria um IFormFile usando o stream
            var formFile = new FormFile(
                baseStream: stream,
                baseStreamOffset: 0,
                length: bytes.Length,
                name: "file",
                fileName: fileName
            )
            {
                Headers = new HeaderDictionary(),
                ContentType = "image/png"
            };

            return formFile;
        }
    }
}
