// EN: Admin Orders REST API Controller.
// VI: Controller REST API cho Admin Orders.

using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OrderService.API.Application.DTOs;
using OrderService.API.Application.Queries;

namespace OrderService.API.Controllers;

/// <summary>
/// EN: Admin Orders API Controller for administrative order management.
/// VI: Controller API Admin Orders cho quản lý đơn hàng dạng admin.
/// </summary>
[ApiController]
[Route("api/v1/admin/orders")]
[Authorize]
public class AdminOrdersController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<AdminOrdersController> _logger;

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

    /// <summary>
    /// EN: List all orders with advanced filtering (Admin only).
    /// VI: Liệt kê tất cả orders với lọc nâng cao (chỉ Admin).
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(PagedResult<OrderSummaryDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<PagedResult<OrderSummaryDto>>> ListAllOrders(
        [FromQuery] Guid? shopId = null,
        [FromQuery] Guid? customerId = null,
        [FromQuery] string? status = null,
        [FromQuery] DateTime? fromDate = null,
        [FromQuery] DateTime? toDate = null,
        [FromQuery] decimal? minAmount = null,
        [FromQuery] decimal? maxAmount = null,
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20,
        CancellationToken cancellationToken = default)
    {
        var query = new AdminListOrdersQuery(
            shopId,
            customerId,
            status,
            fromDate,
            toDate,
            minAmount,
            maxAmount,
            page,
            pageSize);

        var result = await _mediator.Send(query, cancellationToken);
        return Ok(result);
    }

    /// <summary>
    /// EN: Get order statistics (Admin only).
    /// VI: Lấy thống kê orders (chỉ Admin).
    /// </summary>
    [HttpGet("stats")]
   [ProducesResponseType(typeof(OrderStatsDto), StatusCodes.Status200OK)]
    public async Task<ActionResult<OrderStatsDto>> GetOrderStats(
        [FromQuery] Guid? shopId = null,
        [FromQuery] DateTime? fromDate = null,
        [FromQuery] DateTime? toDate = null,
        CancellationToken cancellationToken = default)
    {
        _logger.LogInformation("EN: Getting order stats / VI: Lấy thống kê orders");

        var query = new GetOrderStatsQuery(shopId, fromDate, toDate);
        var stats = await _mediator.Send(query, cancellationToken);
        return Ok(stats);
    }

    /// <summary>
    /// EN: Export orders to CSV (Admin only).
    /// VI: Xuất orders ra CSV (chỉ Admin).
    /// </summary>
    [HttpGet("export")]
    [ProducesResponseType(typeof(FileResult), StatusCodes.Status200OK)]
    public async Task<IActionResult> ExportOrders(
        [FromQuery] Guid? shopId = null,
        [FromQuery] DateTime? fromDate = null,
        [FromQuery] DateTime? toDate = null,
        CancellationToken cancellationToken = default)
    {
        _logger.LogInformation("EN: Exporting orders / VI: Xuất orders");

        var query = new ExportOrdersQuery(shopId, fromDate, toDate);
        var export = await _mediator.Send(query, cancellationToken);
        var bytes = System.Text.Encoding.UTF8.GetBytes(export.CsvContent);

        return File(bytes, "text/csv", export.FileName);
    }
}
