using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SolutionErp.Application.Common.Interfaces;
using SolutionErp.Application.Hrm;

namespace SolutionErp.Api.Controllers;

// Phase 11 P11-B Wave 1 (Mig 42 — S43) — Số dư phép theo năm.
// /my = mọi user đăng nhập (xem phép của chính mình). Admin endpoint (xem user khác +
// điều chỉnh) dùng [Authorize(Roles = "Admin")] — mirror HrmConfigsController convention
// (HRM write/admin = Roles "Admin", KHÔNG menu policy).
[ApiController]
[Route("api/leave-balances")]
[Authorize]
public class LeaveBalancesController(IMediator mediator, IDateTime clock) : ControllerBase
{
    [HttpGet("my")]
    public async Task<IActionResult> GetMy([FromQuery] int? year)
        => Ok(await mediator.Send(new GetMyLeaveBalancesQuery(year ?? clock.Now.Year)));

    [HttpGet]
    [Authorize(Roles = "Admin")]
    public async Task<IActionResult> GetForUser([FromQuery] Guid userId, [FromQuery] int? year)
        => Ok(await mediator.Send(new GetUserLeaveBalancesQuery(userId, year ?? clock.Now.Year)));

    [HttpPut("adjust")]
    [Authorize(Roles = "Admin")]
    public async Task<IActionResult> Adjust([FromBody] AdjustLeaveBalanceBody body)
    {
        await mediator.Send(new AdjustLeaveBalanceCommand(
            body.UserId, body.LeaveTypeId, body.Year, body.EntitledDays, body.AdjustmentDays));
        return NoContent();
    }

    public record AdjustLeaveBalanceBody(
        Guid UserId,
        Guid LeaveTypeId,
        int Year,
        decimal? EntitledDays,
        decimal? AdjustmentDays);
}
