using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SolutionErp.Application.Office;

namespace SolutionErp.Api.Controllers;

// Phase 10.3 G-O3 (S37 2026-05-28) — Đề xuất REST endpoint.
// Class-level [Authorize] — any authenticated user can list/create/view.
// Per-action ownership/role enforcement trong handler (Drafter OR Admin for write;
// Approver-of-current-Level OR Admin for approve/reject/return).
[ApiController]
[Route("api/proposals")]
[Authorize]
public class ProposalsController(IMediator mediator) : ControllerBase
{
    [HttpGet]
    public async Task<IActionResult> GetList(
        [FromQuery] int? status,
        [FromQuery] Guid? departmentId,
        [FromQuery] Guid? drafterUserId,
        [FromQuery] bool inboxOnly = false,
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 50,
        [FromQuery] string? search = null)
        => Ok(await mediator.Send(new GetProposalsQuery(status, departmentId, drafterUserId, inboxOnly, page, pageSize, search)));

    [HttpGet("{id:guid}")]
    public async Task<IActionResult> GetById(Guid id)
    {
        var dto = await mediator.Send(new GetProposalByIdQuery(id));
        return dto is null ? NotFound() : Ok(dto);
    }

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CreateProposalCommand cmd)
    {
        var id = await mediator.Send(cmd);
        return CreatedAtAction(nameof(GetById), new { id }, new { id });
    }

    [HttpPut("{id:guid}")]
    public async Task<IActionResult> Update(Guid id, [FromBody] UpdateProposalDraftBody body)
    {
        await mediator.Send(new UpdateProposalDraftCommand(id, body.Title, body.Description,
            body.AmountEstimate, body.DepartmentId, body.ApprovalWorkflowId));
        return NoContent();
    }

    [HttpPost("{id:guid}/submit")]
    public async Task<IActionResult> Submit(Guid id)
    {
        await mediator.Send(new SubmitProposalCommand(id));
        return NoContent();
    }

    [HttpPost("{id:guid}/approve")]
    public async Task<IActionResult> Approve(Guid id, [FromBody] ApprovalActionBody body)
    {
        await mediator.Send(new ApproveProposalCommand(id, body.Comment));
        return NoContent();
    }

    [HttpPost("{id:guid}/reject")]
    public async Task<IActionResult> Reject(Guid id, [FromBody] ApprovalActionBody body)
    {
        await mediator.Send(new RejectProposalCommand(id, body.Comment));
        return NoContent();
    }

    [HttpPost("{id:guid}/return")]
    public async Task<IActionResult> Return(Guid id, [FromBody] ApprovalActionBody body)
    {
        await mediator.Send(new ReturnProposalCommand(id, body.Comment));
        return NoContent();
    }

    public record UpdateProposalDraftBody(
        string Title,
        string? Description,
        decimal? AmountEstimate,
        Guid? DepartmentId,
        Guid? ApprovalWorkflowId);

    public record ApprovalActionBody(string? Comment);
}
