using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Application.Abstractions.Payment;
using Domain.Entities.Payments;
using Microsoft.Extensions.Options;
using SharedKernel;

namespace Application.Features.Api.Payment.CreateOrder;

internal sealed class Handler(
    IAppDbContext db,
    IDanalPayService danalPay,
    IOptions<AppSettings> options
) : IQueryHandler<Command, Response>
{
    public async Task<Response> Handle(Command r, CancellationToken ct)
    {
        var settings = options.Value;
        var baseUrl = settings.App.FrontURL?.TrimEnd('/') ?? settings.App.BaseURL?.TrimEnd('/') ?? "https://localhost:3000";

        // 주문번호 생성
        var orderID = $"DPOT-{DateTime.UtcNow:yyyyMMddHHmmss}-{r.MemberID}-{Random.Shared.Next(1000, 9999)}";

        // 다날 클라이언트 설정 (CPID 획득)
        var config = await danalPay.GetClientConfigAsync(ct);

        // 엔티티 생성
        var order = PaymentOrder.Create(r.MemberID, orderID, config.MerchantID, r.Amount, r.PaymentMethod);

        await db.PaymentOrder.AddAsync(order);
        await db.SaveChangesAsync(ct);

        return new Response(
            orderID,
            config.ClientKey,
            config.MerchantID,
            order.Amount,
            order.PointAmount,
            order.VatAmount,
            $"{baseUrl}/api/payment/success?orderId={orderID}",
            $"{baseUrl}/api/payment/fail?orderId={orderID}"
        );
    }
}