<?php

namespace App\Http\Controllers;

use App\Settings\SettingsRegistry;
use Illuminate\Http\Request;

class SettingsController extends Controller
{
    public function show(Request $request)
    {
        $user     = $request->user();
        $current  = array_merge(SettingsRegistry::defaults(), $user->settings ?? []);
        $schema   = SettingsRegistry::schema();

        $fields = array_map(fn($field) => array_merge($field, [
            'value' => $current[$field['key']] ?? $field['default'],
        ]), $schema);

        return response()->json(['fields' => $fields]);
    }

    public function update(Request $request)
    {
        $validated = $request->validate(SettingsRegistry::validationRules());
        $request->user()->updateSettings($validated['settings']);
        return response()->json(['message' => 'Settings saved.']);
    }

    public function updateSingle(Request $request, string $key)
    {
        $validated = $request->validate([
            'value' => ['required'],
        ]);

        $request->user()->updateSetting($key, $validated['value']);

        return response()->json(['message' => 'Setting saved.']);
    }
}
