using Asp.Versioning;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TakeoutSaaS.Application.App.Payments.Commands;
using TakeoutSaaS.Application.App.Stores.Services;
using TakeoutSaaS.Domain.Payments.Enums;
using TakeoutSaaS.Shared.Abstractions.Results;
using TakeoutSaaS.Shared.Web.Api;

namespace TakeoutSaaS.TenantApi.Controllers;

/// <summary>
/// 支付回调接口。
/// </summary>
[ApiVersion("1.0")]
[Route("api/tenant/v{version:apiVersion}/payment/callback")]
public sealed class PaymentCallbackController(
    IMediator mediator,
    StoreContextService storeContextService) : BaseApiController
{
    /// <summary>
    /// 微信支付回调（预留，签名验证后续接入 SDK）。
    /// </summary>
    [HttpPost("wechat")]
    [AllowAnonymous]
    public async Task<IActionResult> WeChatCallback(CancellationToken cancellationToken)
    {
        // TODO: 接入微信支付 V3 SDK 后实现签名验证与报文解析
        return Ok(new { code = "SUCCESS", message = "成功" });
    }

    /// <summary>
    /// 支付宝回调（预留，签名验证后续接入 SDK）。
    /// </summary>
    [HttpPost("alipay")]
    [AllowAnonymous]
    public async Task<IActionResult> AlipayCallback(CancellationToken cancellationToken)
    {
        // TODO: 接入支付宝 RSA2 SDK 后实现签名验证与报文解析
        return Ok("success");
    }

    /// <summary>
    /// 内部模拟支付回调（仅开发环境）。
    /// </summary>
    [HttpPost("internal")]
    [Authorize]
    public async Task<ApiResponse<bool>> InternalCallback(
        [FromBody] InternalPaymentCallbackRequest request,
        CancellationToken cancellationToken)
    {
        var (_, tenantId, _) = storeContextService.GetRequiredContext();

        var result = await mediator.Send(new ProcessPaymentCallbackCommand
        {
            OrderNo = request.OrderNo,
            ChannelTransactionId = request.TransactionId ?? $"internal-{Guid.NewGuid():N}",
            Method = request.Method ?? PaymentMethod.WeChatPay,
            Amount = request.Amount,
            PaidAt = request.PaidAt ?? DateTime.UtcNow,
            TenantId = tenantId,
            RawPayload = "internal-test"
        }, cancellationToken);

        return ApiResponse<bool>.Ok(result);
    }
}

/// <summary>
/// 内部模拟支付回调请求体。
/// </summary>
public sealed record InternalPaymentCallbackRequest
{
    /// <summary>
    /// 订单号。
    /// </summary>
    public required string OrderNo { get; init; }

    /// <summary>
    /// 支付金额。
    /// </summary>
    public required decimal Amount { get; init; }

    /// <summary>
    /// 支付流水号（可选）。
    /// </summary>
    public string? TransactionId { get; init; }

    /// <summary>
    /// 支付方式（可选，默认微信）。
    /// </summary>
    public PaymentMethod? Method { get; init; }

    /// <summary>
    /// 支付时间（可选，默认当前时间）。
    /// </summary>
    public DateTime? PaidAt { get; init; }
}
