<?php

namespace App\Models;

use App\Enums\LegalDocumentType;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class LegalDocument extends Model
{
    /** @use HasFactory<\Database\Factories\LegalDocumentFactory> */
    use HasFactory;

    protected $fillable = [
        'slug',
        'type',
        'version',
        'title',
        'content',
        'is_active',
        'published_at',
    ];

    public function scopePublic(Builder $query): Builder
    {
        return $query
            ->where('is_active', true)
            ->whereNotNull('published_at')
            ->where('published_at', '<=', now());
    }

    public function scopeForSlug(Builder $query, string $slug): Builder
    {
        return $query->where('slug', $slug);
    }

    public static function publicForSlug(string $slug): ?self
    {
        return self::query()
            ->public()
            ->forSlug($slug)
            ->latest('version')
            ->first();
    }

    public function createNextVersion(): self
    {
        $nextVersion = ((int) self::query()
            ->where('slug', $this->slug)
            ->max('version')) + 1;

        return self::query()->create([
            'slug' => $this->slug,
            'type' => $this->type,
            'version' => $nextVersion,
            'title' => $this->title,
            'content' => $this->content,
            'is_active' => false,
            'published_at' => null,
        ]);
    }

    protected static function booted(): void
    {
        static::saved(function (LegalDocument $document): void {
            if (! $document->is_active) {
                return;
            }

            static::query()
                ->where('slug', $document->slug)
                ->whereKeyNot($document->getKey())
                ->where('is_active', true)
                ->update(['is_active' => false]);
        });
    }

    protected function casts(): array
    {
        return [
            'type' => LegalDocumentType::class,
            'version' => 'integer',
            'title' => 'array',
            'content' => 'array',
            'is_active' => 'boolean',
            'published_at' => 'datetime',
        ];
    }
}
