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)
        {
            request ??= new FlashcardGenerateRequest();
            if (request.FilePaths is null || request.FilePaths.Count == 0)
            {
                throw new UserException("Selecione ao menos um arquivo para gerar flashcards.");
            }

            var libraries = await _flashcardService.GenerateFlashcardsAsync(request);
            return Ok(new { libraries });
        }

        [HttpGet("libraries")]
        public async Task<IActionResult> GetLibraries()
        {
            var libraries = await _flashcardService.GetLibrariesAsync();
            return Ok(libraries);
        }

        [HttpGet("rag-status")]
        public async Task<IActionResult> GetRagStatus()
        {
            var dashboard = await _flashcardService.GetRagStatusAsync();
            return Ok(dashboard);
        }

        [HttpGet("libraries/{id:long}")]
        public async Task<IActionResult> GetLibraryById([FromRoute] long id)
        {
            var library = await _flashcardService.GetLibraryByIdAsync(id);
            if (library is null)
            {
                return NotFound(new { error = "Biblioteca de flashcards nao encontrada." });
            }

            return Ok(library);
        }

        [HttpPost("review-session")]
        public async Task<IActionResult> BuildReviewSession([FromBody] FlashcardReviewSessionRequest request)
        {
            request ??= new FlashcardReviewSessionRequest();
            var cards = await _flashcardService.BuildReviewSessionAsync(request);
            return Ok(new { cards });
        }

        [HttpPost("review-answer")]
        public async Task<IActionResult> RecordReviewAnswer([FromBody] FlashcardReviewAnswerRequest request)
        {
            request ??= new FlashcardReviewAnswerRequest();
            await _flashcardService.RecordReviewAnswerAsync(request.CardId, request.Correct);
            return Ok(new { success = true });
        }
    }
}
