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

namespace SolutionErp.Api.Controllers;

// Quy trình duyệt MỚI (Mig 22 — Session 17, 2026-05-08).
// Schema riêng để UAT, KHÔNG đụng WorkflowDefinition cũ.
// Authorization split:
//   - GET Overview: chỉ cần authenticated — Drafter cần list workflow để pick
//     lúc create PE/HĐ (read-only, không expose business data nhạy cảm).
//   - POST/DELETE: policy "Workflows.Create" — admin-only Designer.
// Bug fix 2026-05-08: trước class-level "Workflows.Read" → Drafter 403 →
// Workspace dropdown empty silent (không thấy sample workflow đã seed).
[ApiController]
[Route("api/approval-workflows-v2")]
[Authorize]
public class ApprovalWorkflowsV2Controller(IMediator mediator) : ControllerBase
{
    [HttpGet]
    public async Task<ActionResult<AwAdminOverviewDto>> Overview(
        [FromQuery] int? applicableType,
        [FromQuery] bool? isUserSelectable,
        CancellationToken ct)
        => Ok(await mediator.Send(new GetAwAdminOverviewQuery(applicableType, isUserSelectable), ct));

    [HttpPost]
    [Authorize(Policy = "Workflows.Create")]
    public async Task<ActionResult<object>> Create([FromBody] CreateAwDefinitionCommand cmd, CancellationToken ct)
    {
        var id = await mediator.Send(cmd, ct);
        return Ok(new { id });
    }

    public record SetUserSelectableBody(bool IsUserSelectable);

    // Mig 25 — admin toggle stick/unstick "cho user pick lúc create phiếu".
    [HttpPatch("{id:guid}/user-selectable")]
    [Authorize(Policy = "Workflows.Create")]
    public async Task<IActionResult> SetUserSelectable(Guid id, [FromBody] SetUserSelectableBody body, CancellationToken ct)
    {
        await mediator.Send(new SetAwUserSelectableCommand(id, body.IsUserSelectable), ct);
        return NoContent();
    }

    [HttpDelete("{id:guid}")]
    [Authorize(Policy = "Workflows.Create")]
    public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
    {
        await mediator.Send(new DeleteAwDefinitionCommand(id), ct);
        return NoContent();
    }
}
