using Distribution.Infra.Authorization; using Distribution.Models; using Microsoft.AspNetCore.Mvc; namespace Distribution.Features.ShopPO; [ApiController] [Route("api/shop-pos")] public class ShopPOController(ShopPOService service, ICurrentUserService currentUser) : ControllerBase { [HttpGet] public async Task GetAll( [FromQuery] Guid? agentId, [FromQuery] Guid? routeId, [FromQuery] Guid? regionId, [FromQuery] Guid? shopId, [FromQuery] bool? confirmed, [FromQuery] ShopPOStatus? status, [FromQuery] int page = 1, [FromQuery] int pageSize = 20) { var result = await service.GetAllAsync(agentId, routeId, regionId, shopId, confirmed, 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] public async Task Create(CreateShopPORequest request, CancellationToken ct) { var userId = currentUser.UserId ?? throw new UnauthorizedAccessException(); try { var result = await service.CreateAsync(request, userId, ct); return CreatedAtAction(nameof(GetById), new { id = result.Id }, result); } catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); } } [HttpPut("{id:guid}/items")] public async Task UpdateItems(Guid id, UpdateShopPOItemsRequest request, CancellationToken ct) { try { var result = await service.UpdateItemsAsync(id, request, ct); return Ok(result); } catch (KeyNotFoundException) { return NotFound(); } catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); } } [HttpPost("{id:guid}/confirm")] public async Task Confirm(Guid id, CancellationToken ct) { var userId = currentUser.UserId ?? throw new UnauthorizedAccessException(); try { var result = await service.ConfirmAsync(id, userId, ct); return Ok(result); } catch (KeyNotFoundException) { return NotFound(); } catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); } } [HttpPost("{id:guid}/confirm-and-create-invoice")] public async Task ConfirmAndCreateInvoice(Guid id, CancellationToken ct) { var userId = currentUser.UserId ?? throw new UnauthorizedAccessException(); try { var result = await service.ConfirmAndCreateInvoiceAsync(id, userId, ct); return Ok(result); } catch (KeyNotFoundException) { return NotFound(); } catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); } } [HttpPost("{id:guid}/cancel")] public async Task Cancel(Guid id, CancellationToken ct) { try { var result = await service.CancelAsync(id, ct); return Ok(result); } catch (KeyNotFoundException) { return NotFound(); } catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); } } }