using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TakeoutSaaS.Application.App.Deliveries.Commands;
using TakeoutSaaS.Application.App.Deliveries.Dto;
using TakeoutSaaS.Application.App.Deliveries.Queries;
using TakeoutSaaS.Domain.Deliveries.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}/deliveries")]
public sealed class DeliveriesController(IMediator mediator) : BaseApiController
{
    /// <summary>
    /// 创建配送单。
    /// </summary>
    /// <param name="command">创建命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>创建后的配送单。</returns>
    [HttpPost]
    [PermissionAuthorize("delivery:create")]
    [ProducesResponseType(typeof(ApiResponse<DeliveryOrderDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<DeliveryOrderDto>> Create([FromBody] CreateDeliveryOrderCommand command, CancellationToken cancellationToken)
    {
        // 1. 创建配送单
        var result = await mediator.Send(command, cancellationToken);

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

    /// <summary>
    /// 查询配送单列表。
    /// </summary>
    /// <param name="orderId">订单 ID。</param>
    /// <param name="status">配送状态。</param>
    /// <param name="page">页码。</param>
    /// <param name="pageSize">每页大小。</param>
    /// <param name="sortBy">排序字段。</param>
    /// <param name="sortDesc">是否倒序。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>配送单分页列表。</returns>
    [HttpGet]
    [PermissionAuthorize("delivery:read")]
    [ProducesResponseType(typeof(ApiResponse<PagedResult<DeliveryOrderDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<PagedResult<DeliveryOrderDto>>> List(
        [FromQuery] long? orderId,
        [FromQuery] DeliveryStatus? status,
        [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 SearchDeliveryOrdersQuery
        {
            OrderId = orderId,
            Status = status,
            Page = page,
            PageSize = pageSize,
            SortBy = sortBy,
            SortDescending = sortDesc
        }, cancellationToken);

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

    /// <summary>
    /// 获取配送单详情。
    /// </summary>
    /// <param name="deliveryOrderId">配送单 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>配送单详情或未找到。</returns>
    [HttpGet("{deliveryOrderId:long}")]
    [PermissionAuthorize("delivery:read")]
    [ProducesResponseType(typeof(ApiResponse<DeliveryOrderDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<DeliveryOrderDto>> Detail(long deliveryOrderId, CancellationToken cancellationToken)
    {
        // 1. 查询配送单详情
        var result = await mediator.Send(new GetDeliveryOrderByIdQuery { DeliveryOrderId = deliveryOrderId }, cancellationToken);

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

    /// <summary>
    /// 更新配送单。
    /// </summary>
    /// <param name="deliveryOrderId">配送单 ID。</param>
    /// <param name="command">更新命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>更新后的配送单或未找到。</returns>
    [HttpPut("{deliveryOrderId:long}")]
    [PermissionAuthorize("delivery:update")]
    [ProducesResponseType(typeof(ApiResponse<DeliveryOrderDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<DeliveryOrderDto>> Update(long deliveryOrderId, [FromBody] UpdateDeliveryOrderCommand command, CancellationToken cancellationToken)
    {
        // 1. 确保命令携带配送单标识
        if (command.DeliveryOrderId == 0)
        {
            command = command with { DeliveryOrderId = deliveryOrderId };
        }

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

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

    /// <summary>
    /// 删除配送单。
    /// </summary>
    /// <param name="deliveryOrderId">配送单 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>删除结果，未找到则返回错误。</returns>
    [HttpDelete("{deliveryOrderId:long}")]
    [PermissionAuthorize("delivery:delete")]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<object>> Delete(long deliveryOrderId, CancellationToken cancellationToken)
    {
        // 1. 执行删除
        var success = await mediator.Send(new DeleteDeliveryOrderCommand { DeliveryOrderId = deliveryOrderId }, cancellationToken);

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