<?php

namespace App\Models;

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

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

    protected $casts = [
        'require_ftps' => 'boolean',
        'allowed_ip_ranges' => 'array',
    ];

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

    public static function current(): self
    {
        return Cache::remember('photobooth.settings', now()->addMinutes(10), function () {
            $defaults = [
                'ftp_port' => config('photobooth.ftp.port', 2121),
                'rate_limit_per_minute' => config('photobooth.rate_limit_per_minute', 20),
                'expiry_grace_days' => config('photobooth.expiry_grace_days', 1),
                'require_ftps' => false,
                'allowed_ip_ranges' => null,
                'control_service_base_url' => config('photobooth.control_service.base_url'),
                'control_service_token_identifier' => null,
            ];

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

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

    public function ftpHost(): ?string
    {
        return config('photobooth.ftp.host');
    }
}
