<?php

namespace App\Services\PromptLandingPageEditor;

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

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

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

        if (! $source->canDuplicate()) {
            throw ValidationException::withMessages([
                'page' => 'This landing page cannot be duplicated until generation is complete.',
            ]);
        }

        return DB::transaction(function () use ($source, $actor): PromptLandingPage {
            $copy = $actor->promptLandingPages()->create([
                'title' => $this->copyTitle($source),
                'website_url' => $source->website_url,
                'purpose' => $source->purpose,
                'status' => 'pending_approval',
                'brief' => $source->brief,
                'html' => $source->html,
                'css' => $source->css,
                'js' => $source->js,
                'prompt_used' => $source->prompt_used,
            ]);

            $this->recordPublishedVersion->ensureOriginal($copy, $actor);

            return $copy;
        });
    }

    private function copyTitle(PromptLandingPage $source): string
    {
        return Str::limit($source->displayTitle().' (copy)', 255, '');
    }
}
