<?php

declare(strict_types=1);

namespace App\Jobs\NovaCards;

use App\Models\NovaCard;
use App\Services\NovaCards\NovaCardPublishModerationService;
use App\Services\NovaCards\NovaCardPlaywrightRenderService;
use App\Services\NovaCards\NovaCardRenderService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class RenderNovaCardPreviewJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(
        public readonly int $cardId,
    ) {
    }

    public function handle(NovaCardRenderService $renderService, NovaCardPlaywrightRenderService $playwrightService, NovaCardPublishModerationService $moderation): void
    {
        $card = NovaCard::query()->with(['backgroundImage', 'user'])->find($this->cardId);
        if (! $card) {
            return;
        }

        // Try the CSS/Playwright renderer first (pixel-perfect match with the editor).
        // Falls back to the GD renderer if Playwright is disabled or encounters an error.
        if ($playwrightService->isAvailable()) {
            try {
                $playwrightService->render($card);
            } catch (\Throwable $e) {
                report($e);
                $renderService->render($card->fresh()->load(['backgroundImage']));
            }
        } else {
            $renderService->render($card);
        }

        $evaluation = $moderation->evaluate($card->fresh()->loadMissing(['originalCard.user', 'rootCard.user']));

        $moderation->applyPublishOutcome($card->fresh(), $evaluation);
    }

    public function failed(\Throwable $exception): void
    {
        $card = NovaCard::query()->find($this->cardId);
        if (! $card) {
            return;
        }

        $card->forceFill([
            'status' => NovaCard::STATUS_DRAFT,
            'moderation_status' => NovaCard::MOD_PENDING,
        ])->save();
    }
}
