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

namespace SolutionErp.Api.Controllers;

[ApiController]
[Route("api/it-tickets")]
[Authorize]
public class ItTicketsController(IMediator mediator) : ControllerBase
{
    [HttpGet]
    public async Task<IActionResult> GetList([FromQuery] int? status, [FromQuery] int? category, [FromQuery] int? priority,
        [FromQuery] Guid? assignedToUserId, [FromQuery] Guid? requesterUserId, [FromQuery] int page = 1, [FromQuery] int pageSize = 50)
        => Ok(await mediator.Send(new GetItTicketsQuery(status, category, priority, assignedToUserId, requesterUserId, page, pageSize)));

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CreateItTicketCommand cmd)
    {
        var id = await mediator.Send(cmd);
        return Created(string.Empty, new { id });
    }

    [HttpPut("{id:guid}/status")]
    public async Task<IActionResult> UpdateStatus(Guid id, [FromBody] UpdateItTicketStatusBody body)
    {
        await mediator.Send(new UpdateItTicketStatusCommand(id, body.Status, body.Resolution));
        return NoContent();
    }

    // P11-D + S54: re-assign ticket cho IT staff. Authz Admin-OR-dept-IT enforce trong handler
    // (controller [Authorize] any-auth — gotcha #44-aware: pipeline mở, handler check fine-grained).
    [HttpPut("{id:guid}/assign")]
    public async Task<IActionResult> Assign(Guid id, [FromBody] AssignItTicketBody body)
    {
        await mediator.Send(new AssignItTicketCommand(id, body.AssignedToUserId));
        return NoContent();
    }

    // S54: danh sách IT staff nhận ticket + cờ canReassign (FE gate nút). [Authorize] any-auth.
    [HttpGet("assignable-staff")]
    public async Task<IActionResult> AssignableStaff()
        => Ok(await mediator.Send(new GetAssignableItStaffQuery()));

    public record UpdateItTicketStatusBody(int Status, string? Resolution);
    public record AssignItTicketBody(Guid AssignedToUserId);
}
