<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Schema;

#[Fillable([
    'key',
    'title',
    'body',
])]
class LegalDocument extends Model
{
    public const TERMS_KEY = 'terminos-y-condiciones';

    public const PRIVACY_KEY = 'politica-de-privacidad';

    public const INVESTMENT_CONTRACT_KEY = 'contrato-de-inversion';

    public function getRouteKeyName(): string
    {
        return 'key';
    }

    /**
     * @return array<string, array{title: string, body: string}>
     */
    public static function defaults(): array
    {
        return [
            self::TERMS_KEY => [
                'title' => 'Términos y condiciones',
                'body' => '<p>Define aquí los términos y condiciones vigentes de la plataforma.</p>',
            ],
            self::PRIVACY_KEY => [
                'title' => 'Política de privacidad',
                'body' => '<p>Define aquí la política de privacidad vigente de la plataforma.</p>',
            ],
            self::INVESTMENT_CONTRACT_KEY => [
                'title' => 'Contrato de inversión',
                'body' => '<p>Define aquí el contrato de inversión vigente para los inversionistas.</p>',
            ],
        ];
    }

    /**
     * @return list<string>
     */
    public static function keys(): array
    {
        return array_keys(self::defaults());
    }

    public static function forKey(string $key): self
    {
        $default = self::defaults()[$key] ?? [
            'title' => str($key)->replace('-', ' ')->title()->toString(),
            'body' => '',
        ];

        return self::query()->firstOrCreate(
            ['key' => $key],
            $default,
        );
    }

    /**
     * @return Collection<int, self>
     */
    public static function configuredDocuments(): Collection
    {
        return collect(self::keys())
            ->map(fn (string $key): self => self::forKey($key));
    }

    /**
     * @return array<int, array{key: string, title: string, href: string}>
     */
    public static function authLinks(): array
    {
        if (! Schema::hasTable('legal_documents')) {
            return [];
        }

        return self::configuredDocuments()
            ->map(fn (self $document): array => [
                'key' => $document->key,
                'title' => $document->title,
                'href' => route('legal-documents.show', $document),
            ])
            ->values()
            ->all();
    }
}
