using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TakeoutSaaS.Application.App.Payments.Commands;
using TakeoutSaaS.Application.App.Payments.Dto;
using TakeoutSaaS.Application.App.Payments.Queries;
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}/payments")]
public sealed class PaymentsController(IMediator mediator) : BaseApiController
{
    /// <summary>
    /// 创建支付记录。
    /// </summary>
    /// <returns>创建的支付记录信息。</returns>
    [HttpPost]
    [PermissionAuthorize("payment:create")]
    [ProducesResponseType(typeof(ApiResponse<PaymentDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<PaymentDto>> Create([FromBody] CreatePaymentCommand command, CancellationToken cancellationToken)
    {
        // 1. 创建支付记录
        var result = await mediator.Send(command, cancellationToken);

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

    /// <summary>
    /// 查询支付记录列表。
    /// </summary>
    /// <returns>支付记录分页列表。</returns>
    [HttpGet]
    [PermissionAuthorize("payment:read")]
    [ProducesResponseType(typeof(ApiResponse<PagedResult<PaymentDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<PagedResult<PaymentDto>>> List(
        [FromQuery] long? orderId,
        [FromQuery] PaymentStatus? 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 SearchPaymentsQuery
        {
            OrderId = orderId,
            Status = status,
            Page = page,
            PageSize = pageSize,
            SortBy = sortBy,
            SortDescending = sortDesc
        }, cancellationToken);

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

    /// <summary>
    /// 获取支付记录详情。
    /// </summary>
    /// <returns>支付记录详情。</returns>
    [HttpGet("{paymentId:long}")]
    [PermissionAuthorize("payment:read")]
    [ProducesResponseType(typeof(ApiResponse<PaymentDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<PaymentDto>> Detail(long paymentId, CancellationToken cancellationToken)
    {
        // 1. 查询支付记录详情
        var result = await mediator.Send(new GetPaymentByIdQuery { PaymentId = paymentId }, cancellationToken);

        // 2. 返回详情或 404
        return result == null
            ? ApiResponse<PaymentDto>.Error(ErrorCodes.NotFound, "支付记录不存在")
            : ApiResponse<PaymentDto>.Ok(result);
    }

    /// <summary>
    /// 更新支付记录。
    /// </summary>
    /// <returns>更新后的支付记录信息。</returns>
    [HttpPut("{paymentId:long}")]
    [PermissionAuthorize("payment:update")]
    [ProducesResponseType(typeof(ApiResponse<PaymentDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<PaymentDto>> Update(long paymentId, [FromBody] UpdatePaymentCommand command, CancellationToken cancellationToken)
    {
        // 1. 确保命令包含支付记录标识
        if (command.PaymentId == 0)
        {
            command = command with { PaymentId = paymentId };
        }

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

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

    /// <summary>
    /// 删除支付记录。
    /// </summary>
    /// <returns>删除结果。</returns>
    [HttpDelete("{paymentId:long}")]
    [PermissionAuthorize("payment:delete")]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<ApiResponse<object>> Delete(long paymentId, CancellationToken cancellationToken)
    {
        // 1. 执行删除
        var success = await mediator.Send(new DeletePaymentCommand { PaymentId = paymentId }, cancellationToken);

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