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

using Asp.Versioning;
using MediatR;
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]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/admin/orders")]
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)
    {
        // EN: For now, if shopId is provided, use ListOrdersByShopQuery
        // VI: Tạm thời, nếu shopId được cung cấp, dùng ListOrdersByShopQuery
        // TODO: Create AdminListOrdersQuery with more filters
        if (shopId.HasValue)
        {
            var query = new ListOrdersByShopQuery(
                shopId.Value,
                status,
                fromDate,
                toDate,
                page,
                pageSize);
            var result = await _mediator.Send(query, cancellationToken);
            return Ok(result);
        }

        // EN: If customerId is provided
        // VI: Nếu customerId được cung cấp
        if (customerId.HasValue)
        {
            var query = new GetOrdersByCustomerQuery(customerId.Value, page, pageSize);
            var result = await _mediator.Send(query, cancellationToken);
            return Ok(result);
        }

        // EN: Return empty for now
        // VI: Trả về rỗng tạm thời
        return Ok(new PagedResult<OrderSummaryDto>(
            new List<OrderSummaryDto>(),
            0,
            pageSize,
            page));
    }

    /// <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");

        // TODO: Implement GetOrderStatsQuery
        // EN: Return mock data for now
        // VI: Trả về dữ liệu giả tạm thời
        var stats = new OrderStatsDto(
            TotalOrders: 0,
            TotalRevenue: 0,
            AverageOrderValue: 0,
            OrdersByStatus: new Dictionary<string, int>()
        );

        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");

        // TODO: Implement export functionality
        // EN: Return empty CSV for now
        // VI: Trả về CSV rỗng tạm thời
        var csv = "OrderId,ShopId,CustomerId,Status,TotalAmount,CreatedAt\n";
        var bytes = System.Text.Encoding.UTF8.GetBytes(csv);

        return File(bytes, "text/csv", $"orders_{DateTime.UtcNow:yyyyMMdd}.csv");
    }
}

/// <summary>
/// EN: Order statistics DTO.
/// VI: DTO thống kê orders.
/// </summary>
public record OrderStatsDto(
    int TotalOrders,
    decimal TotalRevenue,
    decimal AverageOrderValue,
    Dictionary<string, int> OrdersByStatus
);
