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

namespace SolutionErp.Api.Controllers;

[ApiController]
[Route("api/ot-requests")]
[Authorize]
public class OtRequestsController(IMediator mediator) : ControllerBase
{
    [HttpGet]
    public async Task<IActionResult> GetList([FromQuery] int? status, [FromQuery] Guid? requesterUserId, [FromQuery] int page = 1, [FromQuery] int pageSize = 50)
        => Ok(await mediator.Send(new GetOtRequestsQuery(status, requesterUserId, page, pageSize)));

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

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CreateOtRequestCommand 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] UpdateOtRequestDraftBody body)
    {
        await mediator.Send(new UpdateOtRequestDraftCommand(id, body.OtDate, body.StartTime,
            body.EndTime, body.Hours, body.Reason, body.OtPolicyId, body.ApprovalWorkflowId));
        return NoContent();
    }

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

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

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

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

    [HttpPut("{id:guid}/workflow")]
    public async Task<IActionResult> SetWorkflow(Guid id, [FromBody] SetWorkflowBody body)
    {
        await mediator.Send(new SetOtRequestWorkflowCommand(id, body.ApprovalWorkflowId));
        return NoContent();
    }

    public record SetWorkflowBody(Guid ApprovalWorkflowId);

    public record UpdateOtRequestDraftBody(
        DateTime OtDate,
        TimeSpan StartTime,
        TimeSpan EndTime,
        decimal Hours,
        string Reason,
        Guid? OtPolicyId,
        Guid? ApprovalWorkflowId);

    public record WorkflowActionBody(string? Comment);
}
