<?php

namespace App\Http\Controllers;

use App\Services\AuditService;
use App\Services\SettingsService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MexcoSuperAdminSettingsController extends Controller
{
    public function __construct(
        private SettingsService $settings,
        private AuditService $audit,
    ) {}

    public function index(): View
    {
        $definitions = $this->settings->definitions();
        $grouped = $this->settings->grouped();
        $values = [];

        foreach ($definitions as $group => $keys) {
            foreach ($keys as $key => $meta) {
                $values[$group][$key] = $this->settings->get($group, $key, $meta['default']);
            }
        }

        return view('super-admin.settings.index', compact('definitions', 'values'));
    }

    public function update(Request $request, string $group): RedirectResponse
    {
        if (! array_key_exists($group, $this->settings->definitions())) {
            abort(404);
        }

        $definitions = $this->settings->definitions()[$group];
        $rules = [];

        foreach ($definitions as $key => $meta) {
            $rule = match ($meta['type']) {
                'integer' => 'nullable|integer|min:0',
                'boolean' => 'nullable|boolean',
                default => 'nullable|string|max:255',
            };
            $rules[$key] = $rule;
        }

        $data = $request->validate($rules);
        $this->settings->updateGroup($group, $data);

        $this->audit->log('settings.updated', 'MexcoPlatformSetting', $group, null, $data);

        return back()->with('success', ucfirst($group).' settings saved.');
    }
}
