<?php

namespace App\Services\Coupons;

use App\Models\CheckoutSession;
use App\Models\CouponRedemption;
use App\Services\GiftVouchers\GiftVoucherService;
use Illuminate\Support\Arr;

class CouponRedemptionService
{
    public function __construct(private readonly GiftVoucherService $giftVouchers) {}

    public function recordSuccess(CheckoutSession $session, array $payload = []): void
    {
        if (! $session->coupon_id) {
            return;
        }

        $transactionId = Arr::get($payload, 'id') ?? $session->paddle_transaction_id;

        $values = [
            'tenant_id' => $session->tenant_id,
            'user_id' => $session->user_id,
            'package_id' => $session->package_id,
            'paddle_transaction_id' => $transactionId,
            'status' => CouponRedemption::STATUS_SUCCESS,
            'failure_reason' => null,
            'amount_discounted' => $session->amount_discount,
            'currency' => $session->currency ?? 'EUR',
            'metadata' => array_filter([
                'session_snapshot' => $session->coupon_snapshot,
                'payload' => $payload,
            ]),
            'redeemed_at' => now(),
        ];

        CouponRedemption::query()->updateOrCreate(
            [
                'coupon_id' => $session->coupon_id,
                'checkout_session_id' => $session->id,
            ],
            $values,
        );

        $session->coupon?->increment('redemptions_count');

        $this->giftVouchers->markRedeemed($session->coupon, $transactionId);
    }

    public function recordFailure(CheckoutSession $session, string $reason): void
    {
        if (! $session->coupon_id) {
            return;
        }

        CouponRedemption::query()->updateOrCreate(
            [
                'coupon_id' => $session->coupon_id,
                'checkout_session_id' => $session->id,
            ],
            [
                'tenant_id' => $session->tenant_id,
                'user_id' => $session->user_id,
                'package_id' => $session->package_id,
                'paddle_transaction_id' => $session->paddle_transaction_id,
                'status' => CouponRedemption::STATUS_FAILED,
                'failure_reason' => $reason,
                'amount_discounted' => $session->amount_discount,
                'currency' => $session->currency ?? 'EUR',
                'metadata' => array_filter([
                    'session_snapshot' => $session->coupon_snapshot,
                ]),
            ],
        );
    }
}
