<?php

namespace App\Support;

use App\Models\LandingPageGeneration;
use App\Models\PromptLandingPage;
use Closure;

class LandingPageSlug
{
    public static function normalize(string $slug): string
    {
        return strtolower(trim($slug));
    }

    public static function isValid(string $slug): bool
    {
        return preg_match('/^[a-z]+(?:-[a-z]+)*$/', $slug) === 1 && strlen($slug) <= 80;
    }

    /**
     * @return list<string|Closure>
     */
    public static function rules(?int $ignorePromptPageId = null, ?int $ignoreGenerationId = null): array
    {
        return [
            'required',
            'string',
            'max:150',
            function (string $attribute, mixed $value, Closure $fail): void {
                if (! is_string($value) || ! self::isValid($value)) {
                    $fail('Use lowercase letters and hyphens only, such as summer-offer.');
                }
            },
            function (string $attribute, mixed $value, Closure $fail) use ($ignorePromptPageId, $ignoreGenerationId): void {
                if (! is_string($value) || ! self::isValid($value)) {
                    return;
                }

                $usedByPromptPage = PromptLandingPage::query()
                    ->where('slug', $value)
                    ->when($ignorePromptPageId !== null, fn ($query) => $query->whereKeyNot($ignorePromptPageId))
                    ->exists();

                $usedByCatalog = LandingPageGeneration::query()
                    ->where('slug', $value)
                    ->when($ignoreGenerationId !== null, fn ($query) => $query->whereKeyNot($ignoreGenerationId))
                    ->exists();

                if ($usedByPromptPage || $usedByCatalog) {
                    $fail('That slug is already used by another landing page.');
                }
            },
        ];
    }
}
