using Microsoft.AspNetCore.Mvc;
using Api.Services.Contracts;
using Rag.Models.Requests;
using Rag.Models.Responses;
using Swashbuckle.AspNetCore.Annotations;
using Shared.Models.Responses;

namespace Api.Controllers;

[ApiController]
[Route("api/rag")]
public sealed class RagController : ControllerBase
{
    private readonly IRagService _ragService;
    private readonly ILogger<RagController> _logger;

    public RagController(IRagService ragService, ILogger<RagController> logger)
    {
        _ragService = ragService;
        _logger = logger;
    }

    [HttpPost("documents")]
    [RequestSizeLimit(10 * 1024 * 1024)]
    [SwaggerOperation(Summary = "Index document (multipart)", Description = "Indexes a PDF file or raw text document using multipart/form-data payload.")]
    [SwaggerResponse(StatusCodes.Status200OK, "Document indexed successfully")]
    [SwaggerResponse(StatusCodes.Status400BadRequest, "Invalid indexing request")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)]
    public async Task<ActionResult<IndexDocumentResponse>> IndexDocument(
        [FromForm] IndexDocumentUploadRequest request,
        CancellationToken ct)
    {
        try
        {
            _logger.LogInformation("Index document request received. HasFile={HasFile}, DocumentType={DocumentType}, Title={Title}, SourceUrl={SourceUrl}",
                request.File is not null, request.DocumentType, request.Title, request.SourceUrl);

            if (request.File is not null)
            {
                var result = await _ragService.IndexPdfAsync(request.File, request.DocumentType, request.Title, request.SourceUrl, ct);
                _logger.LogInformation("Indexed PDF document. DocumentId={DocumentId}, DocumentType={DocumentType}, Chunks={Chunks}, Cached={Cached}",
                    result.DocumentId, result.DocumentType, result.Chunks, result.Cached);
                return Ok(result);
            }

            var textResult = await _ragService.IndexTextAsync(new IndexDocumentRequest
            {
                Text = request.Text,
                DocumentType = request.DocumentType,
                Title = request.Title,
                SourceUrl = request.SourceUrl
            }, ct);
            _logger.LogInformation("Indexed text document. DocumentId={DocumentId}, DocumentType={DocumentType}, Chunks={Chunks}, Cached={Cached}",
                textResult.DocumentId, textResult.DocumentType, textResult.Chunks, textResult.Cached);
            return Ok(textResult);
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning(ex, "Invalid document indexing request.");
            return BadRequest(new ErrorResponse { Error = ex.Message, Code = "invalid_request" });
        }
    }

    [HttpPost("documents/json")]
    [SwaggerOperation(Summary = "Index document (JSON)", Description = "Indexes a text document sent as JSON.")]
    [SwaggerResponse(StatusCodes.Status200OK, "JSON document indexed successfully")]
    [SwaggerResponse(StatusCodes.Status400BadRequest, "Invalid JSON indexing request")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)]
    public async Task<ActionResult<IndexDocumentResponse>> IndexJsonDocument([FromBody] IndexDocumentRequest request, CancellationToken ct)
    {
        try
        {
            _logger.LogInformation("JSON document indexing request received. DocumentType={DocumentType}, Title={Title}, SourceUrl={SourceUrl}",
                request.DocumentType, request.Title, request.SourceUrl);
            var result = await _ragService.IndexTextAsync(request, ct);
            _logger.LogInformation("Indexed JSON document. DocumentId={DocumentId}, DocumentType={DocumentType}, Chunks={Chunks}, Cached={Cached}",
                result.DocumentId, result.DocumentType, result.Chunks, result.Cached);
            return Ok(result);
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning(ex, "Invalid JSON document indexing request.");
            return BadRequest(new ErrorResponse { Error = ex.Message, Code = "invalid_request" });
        }
    }

    [HttpPost("search")]
    [SwaggerOperation(Summary = "Semantic search", Description = "Performs semantic retrieval over indexed documents.")]
    [SwaggerResponse(StatusCodes.Status200OK, "Search results returned")]
    [SwaggerResponse(StatusCodes.Status400BadRequest, "Invalid search request")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)]
    public async Task<ActionResult<SearchResponse>> Search([FromBody] SearchRequest request, CancellationToken ct)
    {
        try
        {
            _logger.LogInformation("Semantic search request received. TargetTypes={TargetTypes}, TopK={TopK}",
                string.Join(',', request.TargetDocumentTypes ?? System.Array.Empty<string>()), request.TopK);
            var result = await _ragService.SearchAsync(request, ct);
            _logger.LogInformation("Semantic search completed. ResultCount={ResultCount}", result.Results.Count);
            return Ok(result);
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning(ex, "Invalid semantic search request.");
            return BadRequest(new ErrorResponse { Error = ex.Message, Code = "invalid_request" });
        }
    }

    [HttpGet("documents/{id}")]
    [SwaggerOperation(Summary = "Get document details", Description = "Returns indexed document details for the provided document id.")]
    [SwaggerResponse(StatusCodes.Status200OK, "Document details returned")]
    [SwaggerResponse(StatusCodes.Status404NotFound, "Document was not found")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)]
    public async Task<ActionResult<RagDocumentDetailsResponse>> GetDocument(string id, CancellationToken ct)
    {
        _logger.LogInformation("Get document request received. DocumentId={DocumentId}", id);
        var document = await _ragService.GetDocumentAsync(id, ct);
        if (document is null)
        {
            _logger.LogWarning("Document not found. DocumentId={DocumentId}", id);
            return NotFound(new ErrorResponse { Error = "Document not found.", Code = "document_not_found" });
        }
        return Ok(document);
    }
}
