<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\SettingsRequest;
use App\Http\Resources\SettingsResource;
use App\Services\SettingsService;
use Illuminate\Http\Request;

class SettingsController extends Controller
{
    public function __construct(
        private readonly SettingsService $settingsService
    ) {}

    public function show(Request $request): SettingsResource
    {
        $profile = $request->user()->profile;

        $currentSettings = $profile?->settings ?? [];

        $settings = $this->settingsService->mergeWithDefaults($currentSettings);

        return new SettingsResource($settings);
    }

    public function update(SettingsRequest $request): SettingsResource
    {
        $profile = $request->user()->profile;

        if (! $profile) {
            abort(422, 'Profile must be created before updating settings.');
        }

        $currentSettings = $this->settingsService->mergeWithDefaults($profile->settings ?? []);

        $newSettings = $this->settingsService->validateAndMerge(
            $currentSettings,
            $request->validated()
        );

        $profile->update(['settings' => $newSettings]);

        return new SettingsResource($newSettings);
    }
}
