<?php

namespace App\Support;

use App\Services\Settings;

enum AppMode: string
{
    case Saas = 'saas';
    case SelfHosted = 'self_hosted';

    public static function current(): self
    {
        return self::from(config('appmode.mode'));
    }

    public static function isSaas(): bool
    {
        return self::current() === self::Saas;
    }

    public static function isSelfHosted(): bool
    {
        return self::current() === self::SelfHosted;
    }

    /**
     * Effective email-verification policy (BOTH modes). The admin's explicit
     * DB toggle (admin → settings → signups) wins in either mode. When the DB
     * row is absent the fallback is mode-aware:
     *  - SaaS → `VERIFY_EMAILS` env (default true) — public signups verify.
     *  - self-hosted → false (opt-in). A fresh single-buyer install hasn't
     *    configured SMTP yet, so requiring verification by default would strand
     *    new sign-ups on the notice page with no deliverable mail; the admin
     *    opts in once SMTP is set. Flipping the toggle enforces it in BOTH modes.
     * Wrapped in try/catch so a settings-table outage during early bootstrap
     * can't take down auth.
     */
    public static function shouldVerifyEmails(): bool
    {
        try {
            $setting = Settings::get('auth.require_email_verification');
            if (is_bool($setting)) {
                return $setting;
            }
        } catch (\Throwable) {
            // Fall through to the mode-aware default.
        }

        return self::isSelfHosted()
            ? false
            : (bool) config('appmode.verify_emails', true);
    }
}
