<?php

namespace App\Support;

use App\Models\SystemSetting;

class SecuritySettings
{
    /**
     * Default security configuration values.
     */
    private static array $defaults = [
        'max_login_attempts' => 5,
        'lockout_minutes' => 1,
        'captcha_enabled' => false,
        'captcha_site_key' => '',
        'captcha_secret_key' => '',
        // Platform-wide 2FA kill switch surfaced on the security
        // settings page (Tab 4 → "Enable Two-Factor Authentication").
        // Previously omitted from this defaults map, which silently
        // dropped the value on save in SecuritySettings::update()
        // — the controller validated and submitted it, but the
        // array_key_exists() guard rejected it before write. Default
        // true preserves the existing UX where 2FA is available
        // unless an admin explicitly disables it org-wide.
        'two_factor_enabled' => false,
        'two_factor_admin_only' => false,
        // 2FA issuer string — shows under the workspace's 2FA QR in
        // every authenticator app. Default left empty here so admins
        // who never set this in Admin → Security see their resolved
        // Site Name (via BrandingHelper::name() at read time) rather
        // than the literal source product name. Previously this
        // defaulted to "MailTrixy", which leaked into every account
        // entry in Google Authenticator / Authy / 1Password.
        'two_factor_issuer' => '',
        'single_session' => false,
        'password_min_length' => 10,
        'password_require_uppercase' => true,
        'password_require_numbers' => true,
        'password_require_symbols' => true,
        'session_lifetime_minutes' => 120,
        'ip_blocking_enabled' => true,
        'location_blocking_enabled' => false,
    ];

    /**
     * Get all security settings merged with defaults.
     */
    public static function get(): array
    {
        $stored = [];
        foreach (self::$defaults as $key => $default) {
            $stored[$key] = SystemSetting::get("security.{$key}", $default);
        }
        return $stored;
    }

    /**
     * Get a specific security setting value.
     */
    public static function getValue(string $key, $default = null)
    {
        return SystemSetting::get("security.{$key}", $default ?? (self::$defaults[$key] ?? null));
    }

    /**
     * Set a security setting value.
     */
    public static function setValue(string $key, $value): void
    {
        SystemSetting::set("security.{$key}", $value);
    }

    /**
     * Update multiple security settings at once.
     */
    public static function update(array $settings): void
    {
        foreach ($settings as $key => $value) {
            if (array_key_exists($key, self::$defaults)) {
                static::setValue($key, $value);
            }
        }
        SystemSetting::clearCache();
    }
}
