<?php

namespace App\Jobs;

use App\Models\Coupon;
use App\Services\Paddle\Exceptions\PaddleException;
use App\Services\Paddle\PaddleDiscountService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class SyncCouponToPaddle implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public function __construct(
        public Coupon $coupon,
        public bool $archive = false,
    ) {}

    public function handle(PaddleDiscountService $discounts): void
    {
        try {
            if ($this->archive) {
                $discounts->archiveDiscount($this->coupon);

                $this->coupon->forceFill([
                    'paddle_discount_id' => null,
                    'paddle_snapshot' => null,
                    'paddle_last_synced_at' => now(),
                ])->save();

                return;
            }

            $data = $discounts->updateDiscount($this->coupon);

            $this->coupon->forceFill([
                'paddle_discount_id' => $data['id'] ?? $this->coupon->paddle_discount_id,
                'paddle_snapshot' => $data,
                'paddle_last_synced_at' => now(),
            ])->save();
        } catch (PaddleException $exception) {
            Log::channel('paddle-sync')->error('Failed syncing coupon to Paddle', [
                'coupon_id' => $this->coupon->id,
                'message' => $exception->getMessage(),
                'status' => $exception->status(),
                'context' => $exception->context(),
            ]);

            $this->coupon->forceFill([
                'paddle_snapshot' => [
                    'error' => $exception->getMessage(),
                    'status' => $exception->status(),
                    'context' => $exception->context(),
                ],
            ])->save();

            throw $exception;
        }
    }
}
