using Microsoft.AspNetCore.Mvc; using Distribution.Infra.Authorization; using Distribution.Models; namespace Distribution.Features.Invoice; [ApiController] [Route("api/invoices")] public class InvoiceController(InvoiceService service, ICurrentUserService currentUser) : ControllerBase { [HttpGet] public async Task GetAll( [FromQuery] Guid? agentId, [FromQuery] Guid? routeId, [FromQuery] Guid? shopId, [FromQuery] InvoiceStatus? status, [FromQuery] int page = 1, [FromQuery] int pageSize = 20) { var result = await service.GetAllAsync(agentId, routeId, shopId, status, page, pageSize); return Ok(result); } [HttpGet("{id:guid}")] public async Task GetById(Guid id) { var result = await service.GetByIdAsync(id); return result is null ? NotFound() : Ok(result); } [HttpPost("{id:guid}/print")] public async Task Print(Guid id, CancellationToken ct) { var userId = currentUser.UserId ?? throw new UnauthorizedAccessException(); try { var result = await service.PrintAsync(id, userId, ct); return Ok(result); } catch (KeyNotFoundException) { return NotFound(); } catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); } } [HttpPost("{id:guid}/finalize")] public async Task Finalize(Guid id, [FromBody] FinalizeInvoiceRequest? request, CancellationToken ct) { var userId = currentUser.UserId ?? throw new UnauthorizedAccessException(); try { var result = await service.FinalizeAsync(id, request ?? new FinalizeInvoiceRequest(), userId, ct); return Ok(result); } catch (KeyNotFoundException) { return NotFound(); } catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); } } }