// EN: Controller for leave request operations.
// VI: Controller cho thao tac yeu cau nghi phep.

using MediatR;
using Microsoft.AspNetCore.Mvc;
using MerchantService.API.Application.Commands.LeaveRequests;
using MerchantService.API.Application.Queries.LeaveRequests;

namespace MerchantService.API.Controllers;

[ApiController]
[Route("api/v1/leave-requests")]
public class LeaveRequestsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<LeaveRequestsController> _logger;

    public LeaveRequestsController(IMediator mediator, ILogger<LeaveRequestsController> logger)
    {
        _mediator = mediator;
        _logger = logger;
    }

    /// <summary>
    /// EN: Get leave requests by staff.
    /// VI: Lay yeu cau nghi phep theo nhan vien.
    /// </summary>
    [HttpGet("staff/{staffId:guid}")]
    public async Task<IActionResult> GetByStaff(Guid staffId, CancellationToken ct = default)
    {
        var result = await _mediator.Send(new GetLeaveRequestsByStaffQuery(staffId), ct);
        return Ok(new { success = true, data = new { items = result } });
    }

    /// <summary>
    /// EN: Get leave requests by shop (for manager).
    /// VI: Lay yeu cau nghi phep theo cua hang (cho quan ly).
    /// </summary>
    [HttpGet("shop/{shopId:guid}")]
    public async Task<IActionResult> GetByShop(Guid shopId, CancellationToken ct = default)
    {
        var result = await _mediator.Send(new GetLeaveRequestsByShopQuery(shopId), ct);
        return Ok(new { success = true, data = new { items = result } });
    }

    /// <summary>
    /// EN: Create a leave request.
    /// VI: Tao yeu cau nghi phep.
    /// </summary>
    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CreateLeaveRequestRequest request, CancellationToken ct = default)
    {
        try
        {
            var id = await _mediator.Send(new CreateLeaveRequestCommand(
                request.StaffId, request.ShopId, request.LeaveType,
                request.StartDate, request.EndDate, request.Reason), ct);
            return Created($"/api/v1/leave-requests/{id}", new { success = true, data = new { id } });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error creating leave request");
            return BadRequest(new { success = false, message = ex.Message });
        }
    }

    /// <summary>
    /// EN: Approve a leave request.
    /// VI: Duyet yeu cau nghi phep.
    /// </summary>
    [HttpPost("{id:guid}/approve")]
    public async Task<IActionResult> Approve(Guid id, [FromBody] ApproveRequest request, CancellationToken ct = default)
    {
        var result = await _mediator.Send(new ApproveLeaveRequestCommand(id, request.ApprovedBy), ct);
        if (!result) return NotFound(new { success = false, message = "Leave request not found" });
        return Ok(new { success = true });
    }

    /// <summary>
    /// EN: Reject a leave request.
    /// VI: Tu choi yeu cau nghi phep.
    /// </summary>
    [HttpPost("{id:guid}/reject")]
    public async Task<IActionResult> Reject(Guid id, [FromBody] RejectRequest request, CancellationToken ct = default)
    {
        var result = await _mediator.Send(new RejectLeaveRequestCommand(id, request.RejectedBy, request.Reason), ct);
        if (!result) return NotFound(new { success = false, message = "Leave request not found" });
        return Ok(new { success = true });
    }
}

public record CreateLeaveRequestRequest(Guid StaffId, Guid ShopId, string LeaveType, DateTime StartDate, DateTime EndDate, string? Reason);
public record ApproveRequest(Guid ApprovedBy);
public record RejectRequest(Guid RejectedBy, string? Reason);
