using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TakeoutSaaS.Application.App.Orders.Commands;
using TakeoutSaaS.Application.App.Orders.Dto;
using TakeoutSaaS.Application.App.Orders.Queries;
using TakeoutSaaS.Domain.Orders.Enums;
using TakeoutSaaS.Domain.Payments.Enums;
using TakeoutSaaS.Module.Authorization.Attributes;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Results;
using TakeoutSaaS.Shared.Web.Api;

namespace TakeoutSaaS.AdminApi.Controllers;

/// <summary>
/// 订单管理。
/// </summary>
[ApiVersion("1.0")]
[Authorize]
[Route("api/admin/v{version:apiVersion}/orders")]
public sealed class OrdersController(IMediator mediator) : BaseApiController
{
    /// <summary>
    /// 创建订单。
    /// </summary>
    /// <returns>创建的订单信息。</returns>
    [HttpPost]
    [PermissionAuthorize("order:create")]
    [ProducesResponseType(typeof(ApiResponse<OrderDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<OrderDto>> Create([FromBody] CreateOrderCommand command, CancellationToken cancellationToken)
    {
        // 1. 创建订单
        var result = await mediator.Send(command, cancellationToken);

        // 2. 返回创建结果
        return ApiResponse<OrderDto>.Ok(result);
    }

    /// <summary>
    /// 查询订单列表。
    /// </summary>
    /// <returns>订单分页列表。</returns>
    [HttpGet]
    [PermissionAuthorize("order:read")]
    [ProducesResponseType(typeof(ApiResponse<PagedResult<OrderDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<PagedResult<OrderDto>>> List(
        [FromQuery] long? storeId,
        [FromQuery] OrderStatus? status,
        [FromQuery] PaymentStatus? paymentStatus,
        [FromQuery] string? orderNo,
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20,
        [FromQuery] string? sortBy = null,
        [FromQuery] bool sortDesc = true,
        CancellationToken cancellationToken = default)
    {
        // 1. 组装查询参数并执行查询
        var result = await mediator.Send(new SearchOrdersQuery
        {
            StoreId = storeId,
            Status = status,
            PaymentStatus = paymentStatus,
            OrderNo = orderNo,
            Page = page,
            PageSize = pageSize,
            SortBy = sortBy,
            SortDescending = sortDesc
        }, cancellationToken);

        // 2. 返回分页结果
        return ApiResponse<PagedResult<OrderDto>>.Ok(result);
    }

    /// <summary>
    /// 获取订单详情。
    /// </summary>
    /// <returns>订单详情。</returns>
    [HttpGet("{orderId:long}")]
    [PermissionAuthorize("order:read")]
    [ProducesResponseType(typeof(ApiResponse<OrderDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<OrderDto>> Detail(long orderId, CancellationToken cancellationToken)
    {
        // 1. 查询订单详情
        var result = await mediator.Send(new GetOrderByIdQuery { OrderId = orderId }, cancellationToken);

        // 2. 返回详情或 404
        return result == null
            ? ApiResponse<OrderDto>.Error(ErrorCodes.NotFound, "订单不存在")
            : ApiResponse<OrderDto>.Ok(result);
    }

    /// <summary>
    /// 更新订单。
    /// </summary>
    /// <returns>更新后的订单信息。</returns>
    [HttpPut("{orderId:long}")]
    [PermissionAuthorize("order:update")]
    [ProducesResponseType(typeof(ApiResponse<OrderDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<OrderDto>> Update(long orderId, [FromBody] UpdateOrderCommand command, CancellationToken cancellationToken)
    {
        // 1. 确保命令包含订单标识
        if (command.OrderId == 0)
        {
            command = command with { OrderId = orderId };
        }

        // 2. 执行更新
        var result = await mediator.Send(command, cancellationToken);

        // 3. 返回更新结果或 404
        return result == null
            ? ApiResponse<OrderDto>.Error(ErrorCodes.NotFound, "订单不存在")
            : ApiResponse<OrderDto>.Ok(result);
    }

    /// <summary>
    /// 删除订单。
    /// </summary>
    /// <returns>删除结果。</returns>
    [HttpDelete("{orderId:long}")]
    [PermissionAuthorize("order:delete")]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<object>> Delete(long orderId, CancellationToken cancellationToken)
    {
        // 1. 执行删除
        var success = await mediator.Send(new DeleteOrderCommand { OrderId = orderId }, cancellationToken);

        // 2. 返回结果或 404
        return success
            ? ApiResponse<object>.Ok(null)
            : ApiResponse<object>.Error(ErrorCodes.NotFound, "订单不存在");
    }
}
