using ERPCore.Domain.Enums;
using ERPCore.Dtos.Common;
using ERPCore.Dtos.Procurement;
using ERPCore.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace ERPCore.Controllers;

/// <summary>RFQ &amp; quotation endpoints (docs/11 §3.2).</summary>
[Route("api/v1/rfqs")]
public sealed class RfqsController : ApiControllerBase
{
    private readonly IRfqService _rfqs;

    public RfqsController(IRfqService rfqs) => _rfqs = rfqs;

    /// <summary>List RFQs, newest first.</summary>
    [HttpGet]
    [ProducesResponseType(typeof(PagedResponse<RfqSummaryDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<PagedResponse<RfqSummaryDto>>> List(
        [FromQuery] PageQuery query, [FromQuery] RfqStatus? status, CancellationToken ct)
        => Ok(await _rfqs.ListAsync(query, status, ct));

    [HttpGet("{rfqId:int}")]
    [ProducesResponseType(typeof(RfqDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<RfqDto>> GetById(int rfqId, CancellationToken ct)
    {
        var dto = await _rfqs.GetAsync(rfqId, ct);
        return dto is null ? NotFound() : Ok(dto);
    }

    [HttpPost]
    [ProducesResponseType(typeof(RfqDto), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
    public async Task<ActionResult<RfqDto>> Create([FromBody] CreateRfqRequest request, CancellationToken ct)
    {
        var dto = await _rfqs.CreateAsync(request, ct);
        return Created($"/api/v1/rfqs/{dto.RfqId}", dto);
    }

    [HttpPost("{rfqId:int}/quotations")]
    [ProducesResponseType(typeof(VendorQuotationDto), StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesResponseType(StatusCodes.Status409Conflict)]
    [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
    public async Task<ActionResult<VendorQuotationDto>> AddQuotation(int rfqId, [FromBody] CreateQuotationRequest request, CancellationToken ct)
    {
        var dto = await _rfqs.AddQuotationAsync(rfqId, request, ct);
        return Created($"/api/v1/rfqs/{rfqId}/quotations/{dto.QuotationId}", dto);
    }

    [HttpGet("{rfqId:int}/comparison")]
    [ProducesResponseType(typeof(RfqComparisonDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<RfqComparisonDto>> Comparison(int rfqId, CancellationToken ct)
        => Ok(await _rfqs.GetComparisonAsync(rfqId, ct));
}
