// EN: Admin Appointments Controller - Admin management and analytics APIs.
// VI: Controller Admin Appointments - APIs quản trị và thống kê.

using Asp.Versioning;
using BookingService.API.Application.DTOs;
using BookingService.API.Application.Queries;
using BookingService.API.Models.Responses;
using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace BookingService.API.Controllers.Admin;

[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/admin/appointments")]
[Produces("application/json")]
// [Authorize(Roles = "Admin,ShopOwner")] // TODO: Add authorization
public class AdminAppointmentsController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<AdminAppointmentsController> _logger;

    public AdminAppointmentsController(IMediator mediator, ILogger<AdminAppointmentsController> logger)
    {
        _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    /// <summary>
    /// EN: Get all appointments with advanced filtering for admin.
    /// VI: Lấy tất cả cuộc hẹn với bộ lọc nâng cao cho admin.
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(ApiResponse<PaginatedList<AppointmentDto>>), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse<PaginatedList<AppointmentDto>>>> GetAllAppointments(
        [FromQuery] Guid? shopId,
        [FromQuery] DateTime? startDate,
        [FromQuery] DateTime? endDate,
        [FromQuery] string? status,
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 50,
        CancellationToken cancellationToken = default)
    {
        if (!shopId.HasValue)
        {
            return BadRequest(ApiResponse<PaginatedList<AppointmentDto>>.Fail("ShopId is required"));
        }

        var query = new GetAppointmentsByShopQuery(shopId.Value, startDate, endDate, status, page, pageSize);
        var result = await _mediator.Send(query, cancellationToken);

        return Ok(ApiResponse<PaginatedList<AppointmentDto>>.Ok(result));
    }

    /// <summary>
    /// EN: Get appointment statistics for a date range.
    /// VI: Lấy thống kê cuộc hẹn theo khoảng thời gian.
    /// </summary>
    [HttpGet("statistics")]
    [ProducesResponseType(typeof(ApiResponse<AppointmentStatisticsDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse<AppointmentStatisticsDto>>> GetStatistics(
        [FromQuery] Guid shopId,
        [FromQuery] DateTime startDate,
        [FromQuery] DateTime endDate,
        CancellationToken cancellationToken = default)
    {
        // EN: Query appointments for date range
        // VI: Query appointments trong khoảng thời gian
        var query = new GetAppointmentsByShopQuery(shopId, startDate, endDate, null, 1, int.MaxValue);
        var appointments = await _mediator.Send(query, cancellationToken);

        // EN: Calculate statistics
        // VI: Tính toán thống kê
        var total = appointments.TotalCount;
        var pending = appointments.Items.Count(a => a.Status == "Pending");
        var confirmed = appointments.Items.Count(a => a.Status == "Confirmed");
        var completed = appointments.Items.Count(a => a.Status == "Completed");
        var cancelled = appointments.Items.Count(a => a.Status == "Cancelled");
        var noShow = appointments.Items.Count(a => a.Status == "NoShow");

        var statistics = new AppointmentStatisticsDto
        {
            TotalAppointments = total,
            PendingAppointments = pending,
            ConfirmedAppointments = confirmed,
            CompletedAppointments = completed,
            CancelledAppointments = cancelled,
            NoShowAppointments = noShow,
            CompletionRate = total > 0 ? (decimal)completed / total * 100 : 0,
            CancellationRate = total > 0 ? (decimal)cancelled / total * 100 : 0
        };

        return Ok(ApiResponse<AppointmentStatisticsDto>.Ok(statistics));
    }
}
