<?php

declare(strict_types=1);

namespace App\Models;

use App\Models\Traits\BelongsToTenant;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class LegalDocument extends Model
{
    use BelongsToTenant;
    use HasUuids;
    use SoftDeletes;

    public const TYPES = ['terms_of_service', 'privacy_policy', 'license', 'refund_policy', 'cookie_policy', 'community_rules'];

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

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'effective_at' => 'date',
            'published_at' => 'datetime',
        ];
    }

    public function acceptances(): HasMany
    {
        return $this->hasMany(LegalAcceptance::class, 'document_id');
    }

    protected static function booted(): void
    {
        static::saving(function (self $model): void {
            if ($model->isDirty('content') || empty($model->content_hash)) {
                $model->content_hash = hash('sha256', (string) $model->content);
            }
        });
    }
}
