using Api.SeaHavenIndustries.Helper; using Data.SeaHavenIndustries; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using SeaHaven.Services.DTOs; using SeaHaven.Services.Interfaces; namespace Api.SeaHavenIndustries.Controllers { [ApiController] [Route("api/vendor-portal")] [Route("api/vendorportal")] public class VendorPortalController : Controller { private const string TokenHeader = "X-Vendor-Token"; private readonly IVendorPortalService _portalService; private readonly ILogger _logger; public VendorPortalController(IVendorPortalService portalService, ILogger logger) { _portalService = portalService; _logger = logger; } [HttpGet("session")] public async Task Session(CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); return Ok(new DataResponse { Status = "Success", Data = session }); } [HttpGet("dispatches")] public async Task ListDispatches([FromQuery] string? status = null, CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); var dispatches = await _portalService.ListDispatchesAsync(session, status, cancellationToken); return Ok(new DataResponse { Status = "Success", Data = dispatches }); } [HttpGet("dispatches/{id:int}")] public async Task GetDispatch(int id, CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); var detail = await _portalService.GetDispatchDetailAsync(session, id, cancellationToken); if (detail == null) return NotFound(new Response { Status = "Error", Message = "Dispatch not found" }); return Ok(new DataResponse { Status = "Success", Data = detail }); } [HttpPost("dispatches/{id:int}/accept")] public async Task Accept(int id, CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); try { var result = await _portalService.AcceptDispatchAsync(session, id, cancellationToken); return Ok(new DataResponse { Status = "Success", Data = result }); } catch (KeyNotFoundException) { return NotFound(new Response { Status = "Error", Message = "Dispatch not found" }); } catch (InvalidOperationException ex) { return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex, "The requested action could not be completed for this dispatch") }); } } [HttpPost("dispatches/{id:int}/refuse")] public async Task Refuse(int id, [FromBody] RefuseRequest? body, CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); try { var result = await _portalService.RefuseDispatchAsync(session, id, body?.Reason, cancellationToken); return Ok(new DataResponse { Status = "Success", Data = result }); } catch (KeyNotFoundException) { return NotFound(new Response { Status = "Error", Message = "Dispatch not found" }); } catch (InvalidOperationException ex) { return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex, "The requested action could not be completed for this dispatch") }); } } [HttpPost("dispatches/{id:int}/status")] public async Task ChangeStatus(int id, [FromBody] ChangeStatusRequest body, CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); try { var result = await _portalService.ChangeStatusAsync(session, id, body?.Status, cancellationToken); return Ok(new DataResponse { Status = "Success", Data = result }); } catch (KeyNotFoundException) { return NotFound(new Response { Status = "Error", Message = "Dispatch not found" }); } catch (InvalidOperationException ex) { return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex, "The requested action could not be completed for this dispatch") }); } } [HttpPost("dispatches/{id:int}/request-cancel")] public async Task RequestCancel(int id, [FromBody] RequestCancelRequest body, CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); try { await _portalService.RequestCancelAsync(session, id, body?.Reason, cancellationToken); return Ok(new DataResponse { Status = "Success", Message = "Cancel request sent to dispatcher" }); } catch (KeyNotFoundException) { return NotFound(new Response { Status = "Error", Message = "Dispatch not found" }); } catch (InvalidOperationException ex) { return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex, "The requested action could not be completed for this dispatch") }); } } [HttpPost("dispatches/{id:int}/checklist/{itemId:int}")] public async Task UpdateChecklistItem(int id, int itemId, [FromBody] ChecklistUpdateRequest body, CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); try { var result = await _portalService.UpdateChecklistItemAsync(session, id, itemId, body.IsCompleted, cancellationToken); return Ok(new DataResponse { Status = "Success", Data = result }); } catch (KeyNotFoundException) { return NotFound(new Response { Status = "Error", Message = "Dispatch not found" }); } catch (InvalidOperationException ex) { return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex, "The requested action could not be completed for this dispatch") }); } } [HttpPost("dispatches/{id:int}/signoff")] public async Task AddSignoff(int id, [FromBody] SignoffRequest body, CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); try { var result = await _portalService.AddSignoffAsync(session, id, body?.SignoffType, body?.Name, body?.Signature, body?.SignatureMethod, cancellationToken); return Ok(new DataResponse { Status = "Success", Data = result }); } catch (KeyNotFoundException) { return NotFound(new Response { Status = "Error", Message = "Dispatch not found" }); } catch (InvalidOperationException ex) { return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex, "The requested action could not be completed for this dispatch") }); } } [HttpPost("dispatches/{id:int}/comments")] public async Task AddComment(int id, [FromBody] CommentRequest body, CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); try { var result = await _portalService.AddCommentAsync(session, id, body?.CommentText, cancellationToken); return Ok(new DataResponse { Status = "Success", Data = result }); } catch (KeyNotFoundException) { return NotFound(new Response { Status = "Error", Message = "Dispatch not found" }); } catch (InvalidOperationException ex) { return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex, "The requested action could not be completed for this dispatch") }); } } [HttpPost("dispatches/{id:int}/uplift-request")] public async Task RequestUplift(int id, [FromBody] UpliftRequestBody body, CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); try { var result = await _portalService.RequestUpliftAsync(session, id, body?.RequestedNTE ?? 0m, body?.Reason, body?.RequestKey, body?.EvidenceDocumentId, cancellationToken); return Ok(new DataResponse { Status = "Success", Data = result }); } catch (KeyNotFoundException) { return NotFound(new Response { Status = "Error", Message = "Dispatch not found" }); } catch (InvalidOperationException ex) { return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex, "The requested action could not be completed for this dispatch") }); } } [HttpPost("dispatches/{id:int}/uplift-request/{requestId:int}/cancel")] public async Task CancelUpliftRequest(int id, int requestId, CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); try { var result = await _portalService.CancelUpliftRequestAsync(session, id, requestId, cancellationToken); return Ok(new DataResponse { Status = "Success", Data = result }); } catch (KeyNotFoundException) { return NotFound(new Response { Status = "Error", Message = "Dispatch not found" }); } catch (InvalidOperationException ex) { return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex, "The requested action could not be completed for this dispatch") }); } } // SH-101: vendor withdraw (canonical) endpoint. [HttpPost("dispatches/{id:int}/uplift-request/{requestId:int}/withdraw")] public async Task WithdrawUpliftRequest(int id, int requestId, CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); try { var result = await _portalService.WithdrawUpliftAsync(session, id, requestId, cancellationToken); return Ok(new DataResponse { Status = "Success", Data = result }); } catch (KeyNotFoundException) { return NotFound(new Response { Status = "Error", Message = "Dispatch not found" }); } catch (InvalidOperationException ex) { return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex, "The requested action could not be completed for this dispatch") }); } } // SH-101: vendor revise endpoint on ChangesRequested. [HttpPost("dispatches/{id:int}/uplift-request/{requestId:int}/revise")] public async Task ReviseUpliftRequest(int id, int requestId, [FromBody] UpliftRequestBody? body, CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); try { var result = await _portalService.ReviseUpliftAsync(session, id, requestId, body?.RequestedNTE ?? 0m, body?.Reason, body?.EvidenceDocumentId, cancellationToken); return Ok(new DataResponse { Status = "Success", Data = result }); } catch (KeyNotFoundException) { return NotFound(new Response { Status = "Error", Message = "Dispatch not found" }); } catch (InvalidOperationException ex) { return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex, "The requested action could not be completed for this dispatch") }); } } [HttpPost("dispatches/{id:int}/completion-documents")] [HttpPost("dispatches/{id:int}/documents")] [RequestSizeLimit(10_000_000)] public async Task UploadCompletionDocument( int id, [FromForm] IFormFile file, [FromForm] int? replacesDocumentId = null, [FromForm] string? purpose = null, CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); try { var result = await _portalService.UploadCompletionDocumentAsync( session, id, file, replacesDocumentId, purpose, cancellationToken); return Ok(new DataResponse { Status = "Success", Data = result }); } catch (KeyNotFoundException) { return NotFound(new Response { Status = "Error", Message = "Dispatch not found" }); } catch (InvalidOperationException ex) { return BadRequest(new Response { Status = "Error", Message = _logger.Sanitize(ex, "The completion document could not be uploaded") }); } } [HttpGet("dispatches/{id:int}/completion-documents/{documentId:int}")] [HttpGet("dispatches/{id:int}/documents/{documentId:int}")] public async Task DownloadCompletionDocument(int id, int documentId, CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); var result = await _portalService.DownloadCompletionDocumentAsync(session, id, documentId, cancellationToken); return result.Outcome switch { VendorDocumentDownloadOutcome.Ok => File(result.Content!, result.ContentType!, result.FileName!), VendorDocumentDownloadOutcome.Locked => StatusCode(StatusCodes.Status423Locked, new Response { Status = "Locked", Message = "The completion document is not available for download yet." }), _ => NotFound(new Response { Status = "Error", Message = "Completion document not found" }) }; } [HttpGet("dispatches/{id:int}/documents/{documentId:int}/status")] public async Task GetDocumentStatus(int id, int documentId, CancellationToken cancellationToken = default) { var session = await ResolveSessionAsync(cancellationToken); if (session == null) return Unauthorized(new Response { Status = "Error", Message = "Invalid or expired token" }); var result = await _portalService.GetDocumentStatusAsync(session, id, documentId, cancellationToken); return result == null ? NotFound(new Response { Status = "Error", Message = "Document not found" }) : Ok(new DataResponse { Status = "Success", Data = result }); } private async Task ResolveSessionAsync(CancellationToken cancellationToken) { if (!Request.Headers.TryGetValue(TokenHeader, out var values)) return null; var token = values.ToString(); return await _portalService.ResolveSessionAsync(token, cancellationToken); } public class ChangeStatusRequest { public string? Status { get; set; } } public class RequestCancelRequest { public string? Reason { get; set; } } public class RefuseRequest { public string? Reason { get; set; } } public class ChecklistUpdateRequest { public bool IsCompleted { get; set; } } public class SignoffRequest { public string? Name { get; set; } public string? Signature { get; set; } public string? SignatureMethod { get; set; } public string? SignoffType { get; set; } } public class CommentRequest { public string? CommentText { get; set; } } public class UpliftRequestBody { public decimal RequestedNTE { get; set; } public string? Reason { get; set; } // SH-101: client idempotency key and supporting evidence. public string? RequestKey { get; set; } public int? EvidenceDocumentId { get; set; } } } }