<?php

use MintyPHP\Http\ApiAuth;
use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;
use MintyPHP\Service\Audit\AuditRecorderInterface;
use MintyPHP\Service\Settings\SettingsApiPolicyGateway;
use MintyPHP\Service\Settings\SettingsAppGateway;
use MintyPHP\Service\Settings\SettingsDefaultsGateway;
use MintyPHP\Service\Settings\SettingsFrontendTelemetryGateway;
use MintyPHP\Service\Settings\SettingsMicrosoftGateway;
use MintyPHP\Service\Settings\SettingsSmtpGateway;
use MintyPHP\Service\Settings\SettingsSystemAuditGateway;
use MintyPHP\Service\Settings\SettingsUserLifecycleGateway;

ApiBootstrap::init();

$request = requestInput();
$method = $request->method();
$settingsAppGateway = app(SettingsAppGateway::class);
$settingsDefaultsGateway = app(SettingsDefaultsGateway::class);
$settingsApiPolicyGateway = app(SettingsApiPolicyGateway::class);
$settingsUserLifecycleGateway = app(SettingsUserLifecycleGateway::class);
$settingsSystemAuditGateway = app(SettingsSystemAuditGateway::class);
$settingsFrontendTelemetryGateway = app(SettingsFrontendTelemetryGateway::class);
$settingsMicrosoftGateway = app(SettingsMicrosoftGateway::class);
$settingsSmtpGateway = app(SettingsSmtpGateway::class);

if ($method === 'GET') {
    ApiResponse::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_API_SETTINGS_VIEW);

    ApiResponse::success([
        'data' => buildSettingsResponse(
            $settingsAppGateway,
            $settingsDefaultsGateway,
            $settingsApiPolicyGateway,
            $settingsUserLifecycleGateway,
            $settingsSystemAuditGateway,
            $settingsFrontendTelemetryGateway,
            $settingsMicrosoftGateway,
            $settingsSmtpGateway,
        ),
    ]);
}

if ($method === 'PUT' || $method === 'PATCH') {
    ApiResponse::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_API_SETTINGS_UPDATE);

    $input = $request->bodyAll();
    $errors = formErrors();
    $beforeSettings = buildSettingsResponse(
        $settingsAppGateway,
        $settingsDefaultsGateway,
        $settingsApiPolicyGateway,
        $settingsUserLifecycleGateway,
        $settingsSystemAuditGateway,
        $settingsFrontendTelemetryGateway,
        $settingsMicrosoftGateway,
        $settingsSmtpGateway,
    );

    // Appearance settings (theme, user-theme toggle, primary color) are NOT
    // accepted here — they are tenant-scoped. See the tenant edit endpoints
    // for per-tenant appearance overrides.
    $setters = [
        'app_title' => static fn (?string $v) => $settingsAppGateway->setAppTitle($v),
        'app_locale' => static fn (?string $v) => $settingsAppGateway->setAppLocale($v),
        'app_registration_enabled' => static fn ($v) => $settingsAppGateway->setRegistrationEnabled((bool) $v),
        'api_token_default_ttl_days' => static fn ($v) => $settingsApiPolicyGateway->setApiTokenDefaultTtlDays($v !== null ? (int) $v : null),
        'api_token_max_ttl_days' => static fn ($v) => $settingsApiPolicyGateway->setApiTokenMaxTtlDays($v !== null ? (int) $v : null),
        'api_cors_allowed_origins' => static fn (?string $v) => $settingsApiPolicyGateway->setApiCorsAllowedOrigins($v),
        'default_tenant_id' => static fn ($v) => $settingsDefaultsGateway->setDefaultTenantId($v !== null ? (int) $v : null),
        'default_role_id' => static fn ($v) => $settingsDefaultsGateway->setDefaultRoleId($v !== null ? (int) $v : null),
        'default_department_id' => static fn ($v) => $settingsDefaultsGateway->setDefaultDepartmentId($v !== null ? (int) $v : null),
        'user_inactivity_deactivate_days' => static fn ($v) => $settingsUserLifecycleGateway->setUserInactivityDeactivateDays($v !== null ? (int) $v : null),
        'user_inactivity_delete_days' => static fn ($v) => $settingsUserLifecycleGateway->setUserInactivityDeleteDays($v !== null ? (int) $v : null),
        'system_audit_enabled' => static fn ($v) => $settingsSystemAuditGateway->setSystemAuditEnabled((bool) $v),
        'system_audit_retention_days' => static fn ($v) => $settingsSystemAuditGateway->setSystemAuditRetentionDays($v !== null ? (int) $v : null),
        'frontend_telemetry_enabled' => static fn ($v) => $settingsFrontendTelemetryGateway->setFrontendTelemetryEnabled((bool) $v),
        'frontend_telemetry_sample_rate' => static fn ($v) => $settingsFrontendTelemetryGateway->setFrontendTelemetrySampleRate(
            $v === null ? null : (is_numeric((string) $v) ? (float) $v : NAN)
        ),
        'frontend_telemetry_allowed_events' => static fn ($v) => $settingsFrontendTelemetryGateway->setFrontendTelemetryAllowedEvents($v),
        'microsoft_shared_client_id' => static fn (?string $v) => $settingsMicrosoftGateway->setMicrosoftSharedClientId($v),
        'microsoft_authority' => static fn (?string $v) => $settingsMicrosoftGateway->setMicrosoftAuthority($v),
        'smtp_host' => static fn (?string $v) => $settingsSmtpGateway->setSmtpHost($v),
        'smtp_port' => static fn ($v) => $settingsSmtpGateway->setSmtpPort($v !== null ? (int) $v : null),
        'smtp_user' => static fn (?string $v) => $settingsSmtpGateway->setSmtpUser($v),
        'smtp_password' => static fn (?string $v) => $settingsSmtpGateway->setSmtpPassword($v),
        'smtp_secure' => static fn (?string $v) => $settingsSmtpGateway->setSmtpSecure($v),
        'smtp_from' => static fn (?string $v) => $settingsSmtpGateway->setSmtpFrom($v),
        'smtp_from_name' => static fn (?string $v) => $settingsSmtpGateway->setSmtpFromName($v),
    ];

    foreach ($input as $key => $value) {
        if (!isset($setters[$key])) {
            continue;
        }
        $ok = $setters[$key]($value);
        if (!$ok) {
            $errors->add($key, 'invalid_value');
        }
    }

    if ($errors->hasAny()) {
        app(AuditRecorderInterface::class)->record('admin.settings.update', 'failed', [
            'actor_user_id' => ApiAuth::userId(),
            'error_code' => 'validation_error',
            'metadata' => ['errors' => array_keys($errors->toArray())],
        ]);
        ApiResponse::validationFromFormErrors($errors);
    }

    $afterSettings = buildSettingsResponse(
        $settingsAppGateway,
        $settingsDefaultsGateway,
        $settingsApiPolicyGateway,
        $settingsUserLifecycleGateway,
        $settingsSystemAuditGateway,
        $settingsFrontendTelemetryGateway,
        $settingsMicrosoftGateway,
        $settingsSmtpGateway,
    );
    app(AuditRecorderInterface::class)->record('admin.settings.update', 'success', [
        'actor_user_id' => ApiAuth::userId(),
        'before' => $beforeSettings,
        'after' => $afterSettings,
    ]);

    ApiResponse::success([
        'data' => $afterSettings,
    ]);
}

ApiResponse::methodNotAllowed();

/**
 * @return array<string, mixed>
 */
function buildSettingsResponse(
    SettingsAppGateway $settingsAppGateway,
    SettingsDefaultsGateway $settingsDefaultsGateway,
    SettingsApiPolicyGateway $settingsApiPolicyGateway,
    SettingsUserLifecycleGateway $settingsUserLifecycleGateway,
    SettingsSystemAuditGateway $settingsSystemAuditGateway,
    SettingsFrontendTelemetryGateway $settingsFrontendTelemetryGateway,
    SettingsMicrosoftGateway $settingsMicrosoftGateway,
    SettingsSmtpGateway $settingsSmtpGateway
): array {
    return [
        'app_title' => $settingsAppGateway->getAppTitle(),
        'app_locale' => $settingsAppGateway->getAppLocale(),
        'app_registration_enabled' => $settingsAppGateway->isRegistrationEnabled(),
        'api_token_default_ttl_days' => $settingsApiPolicyGateway->getApiTokenDefaultTtlDays(),
        'api_token_max_ttl_days' => $settingsApiPolicyGateway->getApiTokenMaxTtlDays(),
        'api_cors_allowed_origins' => $settingsApiPolicyGateway->getApiCorsAllowedOrigins(),
        'default_tenant_id' => $settingsDefaultsGateway->getDefaultTenantId(),
        'default_role_id' => $settingsDefaultsGateway->getDefaultRoleId(),
        'default_department_id' => $settingsDefaultsGateway->getDefaultDepartmentId(),
        'user_inactivity_deactivate_days' => $settingsUserLifecycleGateway->getUserInactivityDeactivateDays(),
        'user_inactivity_delete_days' => $settingsUserLifecycleGateway->getUserInactivityDeleteDays(),
        'system_audit_enabled' => $settingsSystemAuditGateway->isSystemAuditEnabled(),
        'system_audit_retention_days' => $settingsSystemAuditGateway->getSystemAuditRetentionDays(),
        'frontend_telemetry_enabled' => $settingsFrontendTelemetryGateway->isFrontendTelemetryEnabled(),
        'frontend_telemetry_sample_rate' => $settingsFrontendTelemetryGateway->getFrontendTelemetrySampleRate(),
        'frontend_telemetry_allowed_events' => $settingsFrontendTelemetryGateway->getFrontendTelemetryAllowedEvents(),
        'microsoft_shared_client_id' => $settingsMicrosoftGateway->getMicrosoftSharedClientId(),
        'microsoft_authority' => $settingsMicrosoftGateway->getMicrosoftAuthority(),
        'smtp_host' => $settingsSmtpGateway->getSmtpHost(),
        'smtp_port' => $settingsSmtpGateway->getSmtpPort(),
        'smtp_user' => $settingsSmtpGateway->getSmtpUser(),
        'smtp_secure' => $settingsSmtpGateway->getSmtpSecure(),
        'smtp_from' => $settingsSmtpGateway->getSmtpFrom(),
        'smtp_from_name' => $settingsSmtpGateway->getSmtpFromName(),
    ];
}
