using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Mindforge.API.Exceptions;
using Mindforge.API.Models.Requests;
using Mindforge.API.Services.Interfaces;

namespace Mindforge.API.Controllers
{
    [ApiController]
    [Route("api/v1/file")]
    public class FileController : ControllerBase
    {
        private readonly IFileService _fileService;

        public FileController(IFileService fileService)
        {
            _fileService = fileService;
        }

        [HttpPost("check")]
        public async Task<IActionResult> CheckFile([FromBody] FileCheckRequest request)
        {
            if (string.IsNullOrWhiteSpace(request.FileContent) || string.IsNullOrWhiteSpace(request.CheckType))
            {
                throw new UserException("FileContent and CheckType are required.");
            }

            try
            {
                var base64Bytes = Convert.FromBase64String(request.FileContent);
                request.FileContent = System.Text.Encoding.UTF8.GetString(base64Bytes);
            }
            catch (FormatException)
            {
                throw new UserException("FileContent must be a valid base64 string.");
            }

            var response = await _fileService.CheckFileAsync(request);
            return Ok(new { result = response });
        }
    }
}
