using DoliMiddlewareApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace DoliMiddlewareApi.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class DocumentController(DocumentService documentService) : ControllerBase
{
    [HttpGet("invoice/{invoiceRef}/pdf")]
    [ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status401Unauthorized)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetInvoicePdf(string invoiceRef)
    {
        var (content, filename) = await documentService.BuildInvoicePdfAsync(invoiceRef);
        return File(content, "application/pdf", filename);
    }

    [HttpGet("list")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status401Unauthorized)]
    public async Task<ActionResult<List<DocumentItem>>> GetDocuments(
        [FromQuery] string modulePart = "invoice",
        [FromQuery] int id = 0)
    {
        if (id <= 0)
            return BadRequest("id parameter is required");

        var documents = await documentService.GetDocumentsAsync(modulePart, id);
        return Ok(documents);
    }

    [HttpGet("download")]
    [ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status401Unauthorized)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
    public async Task<IActionResult> DownloadDocument(
        [FromQuery] string modulePart = "invoice",
        [FromQuery] string file = "")
    {
        if (string.IsNullOrEmpty(file))
            return BadRequest("file parameter is required");

        var (content, filename, contentType) = await documentService.DownloadDocumentAsync(modulePart, file);
        return File(content, contentType, filename);
    }
}