<?php

declare(strict_types=1);

namespace ImovelZapAi\SuperAdmin\Infrastructure\Http\Controllers\Web;

use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use ImovelZapAi\SuperAdmin\Application\Services\PlatformAuditLogger;
use ImovelZapAi\SuperAdmin\Application\Services\PlatformSettingsStore;

final class PlatformSettingsController
{
    public function index(PlatformSettingsStore $settings): View
    {
        return view('super-admin.settings.index', [
            'maintenance' => $settings->maintenanceMode(),
            'featureFlags' => $settings->featureFlags(),
            'ipAllowlist' => implode("\n", $settings->ipAllowlist()),
        ]);
    }

    public function update(Request $request, PlatformSettingsStore $settings, PlatformAuditLogger $audit): RedirectResponse
    {
        $data = $request->validate([
            'maintenance_mode' => ['nullable', 'boolean'],
            'ip_allowlist' => ['nullable', 'string'],
            'feature_flags' => ['nullable', 'array'],
        ]);

        $settings->set('maintenance_mode', $request->boolean('maintenance_mode'));

        $ips = array_values(array_filter(array_map('trim', preg_split('/[\s,]+/', (string) ($data['ip_allowlist'] ?? '')) ?: [])));
        $settings->set('ip_allowlist', $ips);

        $flags = [];
        foreach ((array) ($data['feature_flags'] ?? []) as $key => $value) {
            $flags[(string) $key] = (bool) $value;
        }
        if ($flags === []) {
            $flags = $settings->featureFlags();
        }
        // Known flags toggles from form checkboxes
        foreach (['ai_auto_reply_default', 'new_signups', 'public_registration'] as $flag) {
            $flags[$flag] = $request->boolean("flag_{$flag}");
        }
        $settings->set('feature_flags', $flags);

        $audit->log('settings.updated', null, null, null, [
            'maintenance_mode' => $request->boolean('maintenance_mode'),
            'flags' => $flags,
        ]);

        return back()->with('status', 'Configurações da plataforma salvas.');
    }
}
