using Core.Interfaces.Stock;
using Documents.Interfaces;
using Documents.Models;
using Domain.Entities;
using Microsoft.AspNetCore.Mvc;

namespace phronCare.API.Controllers.Stock
{
    [Route("api/[controller]")]
    [ApiController]
    public class ExpeditionController : ControllerBase
    {
        private readonly IExpeditionDom _expeditionService;      // ← este es _expeditionService
        private readonly IDocumentTemplateService _documentTemplateService;

        public ExpeditionController(
            IDocumentTemplateService documentTemplateService,
            IExpeditionDom expeditionService)
        {
            _documentTemplateService = documentTemplateService
                ?? throw new ArgumentNullException(nameof(documentTemplateService));
            _expeditionService = expeditionService
                ?? throw new ArgumentNullException(nameof(expeditionService));
        }

        #region Endpoint de emision de expedicion (encabezado + detalles)
        [HttpPost("createfull")]
        public async Task<IActionResult> CreateFullExpedition([FromBody] CreateFullExpeditionRequest request)
        {
            try
            {
                if (request == null || request.Expedition == null)
                    return BadRequest("El payload no puede contener elementos nulos.");

                // Delegamos al service, que ahora arma el grafo y llama al repo atómico
                var (id, number) = await _expeditionService.CreateAndIssueAsync(
                    request.Expedition,
                    request.Expedition.PhLsmExpeditionDetails, // detalles vienen dentro, igual que en Quotes
                    request.FormSeriesId);

                // <<< Simetría absoluta con QuoteController: objeto anónimo >>>
                return Ok(new { Success = true, Id = id, ExpeditionNumber = number });
            }
            catch (InvalidOperationException ex)
            {
                return BadRequest($"Error de negocio: {ex.Message}");
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Ocurrió un error interno: {ex.Message}");
            }
        }
        #endregion

        /// <summary>  
        /// Genera y devuelve un archivo PDF correspondiente al presupuesto especificado por su ID.  
        /// </summary>
        [HttpGet("{id}/pdf")]
        public async Task<IActionResult> GetQuotePdf(int id)
        {
            var expedition = await _expeditionService.GetDtoByIdAsync(id);

            if (expedition == null)
                return NotFound($"Expedicion con ID {id} no encontrado.");

            var pdfBytes = await _documentTemplateService.GenerateDocumentAsync(new DocumentGenerationRequest
            {
                Model = expedition,
                DocumentType = DocumentType.Expedition
            });

            return File(pdfBytes, "application/pdf", $"Expedicion_{expedition.Expeditionnumber}.pdf");
        }
    }
    public class CreateFullExpeditionRequest
    {
        public ELSExpeditionHeader Expedition { get; set; } = default!;
        public int FormSeriesId { get; set; }
    }
}
