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

namespace SolutionErp.Api.Controllers;

[ApiController]
[Route("api/attendances")]
[Authorize]
public class AttendancesController(IMediator mediator, IAttendanceReportExcelExporter excelExporter) : ControllerBase
{
    [HttpPost("check-in")]
    public async Task<IActionResult> CheckIn([FromBody] CheckInCommand cmd)
    {
        var id = await mediator.Send(cmd);
        return Created(string.Empty, new { id });
    }

    [HttpPost("check-out")]
    public async Task<IActionResult> CheckOut([FromBody] CheckOutCommand cmd)
    {
        await mediator.Send(cmd);
        return NoContent();
    }

    [HttpGet("me")]
    public async Task<IActionResult> GetMyMonth([FromQuery] int? year, [FromQuery] int? month)
    {
        var now = DateTime.Now;
        return Ok(await mediator.Send(new GetMyAttendanceQuery(year ?? now.Year, month ?? now.Month)));
    }

    // P11-E: báo cáo chấm công tháng + OT quy đổi — admin-only (MVP).
    [HttpGet("report")]
    [Authorize(Roles = "Admin")]
    public async Task<IActionResult> GetReport([FromQuery] int year, [FromQuery] int month, [FromQuery] Guid? departmentId)
        => Ok(await mediator.Send(new GetAttendanceReportQuery(year, month, departmentId)));

    [HttpGet("report/excel")]
    [Authorize(Roles = "Admin")]
    public async Task<IActionResult> GetReportExcel([FromQuery] int year, [FromQuery] int month, [FromQuery] Guid? departmentId)
    {
        var report = await mediator.Send(new GetAttendanceReportQuery(year, month, departmentId));
        var result = excelExporter.Export(report);
        return File(result.Content, result.ContentType, result.FileName);
    }
}
