<?php

namespace App\Services\PromptLandingPageEditor;

use App\Models\PromptLandingPage;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class OverrideWithPage
{
    public function __construct(private RecordPublishedVersion $recordPublishedVersion) {}

    public function handle(PromptLandingPage $target, PromptLandingPage $source, User $actor): PromptLandingPage
    {
        abort_unless($target->user_id === $actor->id, 403);
        abort_unless($source->user_id === $actor->id, 404);

        if ($target->id === $source->id) {
            throw ValidationException::withMessages([
                'source_page' => 'Choose a different landing page to override with.',
            ]);
        }

        if (! $target->canReceiveOverride()) {
            throw ValidationException::withMessages([
                'page' => 'Wait until this landing page finishes generating before replacing it.',
            ]);
        }

        if (! $source->isReady() || $source->isBusy()) {
            throw ValidationException::withMessages([
                'source_page' => 'Choose a finished landing page to copy from.',
            ]);
        }

        return DB::transaction(function () use ($target, $source, $actor): PromptLandingPage {
            $this->recordPublishedVersion->snapshotLive($target, $actor);

            $target->update([
                'html' => $source->html,
                'css' => $source->css,
                'js' => $source->js,
            ]);

            $this->recordPublishedVersion->snapshotLive($target->refresh(), $actor);

            $target->editorDraft?->delete();

            return $target;
        });
    }
}
