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

namespace SolutionErp.Api.Controllers;

// Phase 10.2 G-O2 (S36) — Phòng họp Booking API.
// Class-level [Authorize]: mọi user đăng nhập được book (multi-tenant office use case).
// Authorization owner-or-admin enforced TRONG handler (UpdateMeetingBookingHandler +
// CancelMeetingBookingHandler) — controller không restrict role.
// Pattern 12-bis cross-module mirror HrmConfigsController.cs (S35 cumulative 10×).

[ApiController]
[Route("api/meeting-bookings")]
[Authorize]
public class MeetingBookingsController(IMediator mediator) : ControllerBase
{
    [HttpGet]
    public async Task<List<MeetingBookingDto>> List(
        [FromQuery] Guid? roomId,
        [FromQuery] DateTime? startDate,
        [FromQuery] DateTime? endDate,
        [FromQuery] bool myOnly,
        CancellationToken ct)
        => await mediator.Send(new GetMeetingBookingsQuery(roomId, startDate, endDate, myOnly), ct);

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

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CreateMeetingBookingCommand body, CancellationToken ct)
    {
        var id = await mediator.Send(body, ct);
        return CreatedAtAction(nameof(GetById), new { id }, new { id });
    }

    [HttpPut("{id:guid}")]
    public async Task<IActionResult> Update(Guid id, [FromBody] UpdateMeetingBookingCommand body, CancellationToken ct)
    {
        if (id != body.Id) return BadRequest("Id mismatch");
        await mediator.Send(body, ct);
        return NoContent();
    }

    [HttpDelete("{id:guid}")]
    public async Task<IActionResult> Cancel(Guid id, CancellationToken ct)
    {
        await mediator.Send(new CancelMeetingBookingCommand(id), ct);
        return NoContent();
    }
}
