<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class GuestPolicySetting extends Model
{
    protected $guarded = [];

    protected $casts = [
        'guest_downloads_enabled' => 'boolean',
        'guest_sharing_enabled' => 'boolean',
        'guest_notification_ttl_hours' => 'integer',
        'guest_upload_visibility' => 'string',
        'per_device_upload_limit' => 'integer',
        'join_token_failure_limit' => 'integer',
        'join_token_failure_decay_minutes' => 'integer',
        'join_token_access_limit' => 'integer',
        'join_token_access_decay_minutes' => 'integer',
        'join_token_download_limit' => 'integer',
        'join_token_download_decay_minutes' => 'integer',
        'join_token_ttl_hours' => 'integer',
        'share_link_ttl_hours' => 'integer',
    ];

    protected static function booted(): void
    {
        static::saved(fn () => static::flushCache());
        static::deleted(fn () => static::flushCache());
    }

    public static function current(): self
    {
        return Cache::remember('guest_policy.settings', now()->addMinutes(10), function () {
            $defaults = [
                'guest_downloads_enabled' => true,
                'guest_sharing_enabled' => true,
                'guest_upload_visibility' => 'review',
                'per_device_upload_limit' => 50,
                'join_token_failure_limit' => (int) config('join_tokens.failure_limit', 10),
                'join_token_failure_decay_minutes' => (int) config('join_tokens.failure_decay_minutes', 5),
                'join_token_access_limit' => (int) config('join_tokens.access_limit', 300),
                'join_token_access_decay_minutes' => (int) config('join_tokens.access_decay_minutes', 1),
                'join_token_download_limit' => (int) config('join_tokens.download_limit', 120),
                'join_token_download_decay_minutes' => (int) config('join_tokens.download_decay_minutes', 1),
                'join_token_ttl_hours' => 168,
                'share_link_ttl_hours' => (int) config('share-links.ttl_hours', 48),
                'guest_notification_ttl_hours' => null,
            ];

            return static::query()->firstOrCreate(['id' => 1], $defaults);
        });
    }

    public static function flushCache(): void
    {
        Cache::forget('guest_policy.settings');
    }
}
