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/flashcard")]
    public class FlashcardController : ControllerBase
    {
        private readonly IFlashcardService _flashcardService;

        public FlashcardController(IFlashcardService flashcardService)
        {
            _flashcardService = flashcardService;
        }

        [HttpPost("generate")]
        public async Task<IActionResult> Generate([FromBody] FlashcardGenerateRequest request)
        {
            if (string.IsNullOrWhiteSpace(request.FileContent) || request.Amount <= 0)
            {
                throw new UserException("FileContent is required and Amount must be greater than 0.");
            }

            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 _flashcardService.GenerateFlashcardsAsync(request);
            return Ok(new { result = response });
        }
    }
}
