<?php

namespace App\Jobs;

use App\Models\Package;
use App\Services\Paddle\PaddleCatalogService;
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\Arr;
use Illuminate\Support\Facades\Log;
use Throwable;

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

    public function __construct(private readonly int $packageId) {}

    public function handle(PaddleCatalogService $catalog): void
    {
        $package = Package::query()->find($this->packageId);

        if (! $package) {
            return;
        }

        if (! $package->paddle_product_id && ! $package->paddle_price_id) {
            Log::channel('paddle-sync')->warning('Paddle pull skipped for package without linkage', [
                'package_id' => $package->id,
            ]);

            return;
        }

        try {
            $product = $package->paddle_product_id ? $catalog->fetchProduct($package->paddle_product_id) : null;
            $price = $package->paddle_price_id ? $catalog->fetchPrice($package->paddle_price_id) : null;

            $snapshot = $package->paddle_snapshot ?? [];
            $snapshot['remote'] = array_filter([
                'product' => $product,
                'price' => $price,
            ], static fn ($value) => $value !== null);

            $package->forceFill([
                'paddle_sync_status' => 'pulled',
                'paddle_synced_at' => now(),
                'paddle_snapshot' => $snapshot,
            ])->save();

            Log::channel('paddle-sync')->info('Paddle package pull completed', [
                'package_id' => $package->id,
            ]);
        } catch (Throwable $exception) {
            Log::channel('paddle-sync')->error('Paddle package pull failed', [
                'package_id' => $package->id,
                'message' => $exception->getMessage(),
                'exception' => $exception,
            ]);

            $snapshot = $package->paddle_snapshot ?? [];
            $snapshot['error'] = array_merge(Arr::get($snapshot, 'error', []), [
                'message' => $exception->getMessage(),
                'class' => $exception::class,
            ]);

            $package->forceFill([
                'paddle_sync_status' => 'pull-failed',
                'paddle_synced_at' => now(),
                'paddle_snapshot' => $snapshot,
            ])->save();

            throw $exception;
        }
    }
}
