using Distribution.Models; using Distribution.Infra.Authorization; using Microsoft.AspNetCore.Mvc; namespace Distribution.Features.LoadingEvent; [ApiController] [Route("api/loading-sheets")] public class LoadingSheetController(LoadingSheetService service, ICurrentUserService currentUser) : ControllerBase { [HttpGet] public async Task GetAll( [FromQuery] Guid? rideId, [FromQuery] LoadingSheetStatus? status, [FromQuery] Guid? routeId, [FromQuery] Guid? regionId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20) { var result = await service.GetAllAsync(rideId, status, routeId, regionId, 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(CreateLoadingSheetRequest request, CancellationToken ct) { // TEMPORARY: currentUser.UserId is always unset due to the broken auth middleware // (testbug.md #28) — fall back to the explicitly supplied user until that's fixed. var userId = currentUser.UserId ?? request.PopulatedByUserId; if (userId is null) return BadRequest(new { error = "PopulatedByUserId is required while auth is unavailable" }); try { var result = await service.CreateAsync(request, userId.Value, ct); return CreatedAtAction(nameof(GetById), new { id = result.Id }, result); } catch (KeyNotFoundException) { return NotFound(); } catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); } } [HttpPut("{id:guid}/items")] public async Task SetItems(Guid id, SetItemsRequest request, CancellationToken ct) { try { var result = await service.SetItemsAsync(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, ConfirmLoadingSheetRequest request, CancellationToken ct) { // TEMPORARY: currentUser.UserId is always unset due to the broken auth middleware // (testbug.md #28) — fall back to the explicitly supplied user until that's fixed. var userId = currentUser.UserId ?? request.ConfirmedByUserId; if (userId is null) return BadRequest(new { error = "ConfirmedByUserId is required while auth is unavailable" }); try { var result = await service.ConfirmAsync(id, userId.Value, ct); return Ok(result); } catch (KeyNotFoundException) { return NotFound(); } catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); } } }