<?php

namespace App\Http\Controllers\Settings;

use App\Enums\DietaryRestriction;
use App\Enums\StylePreference;
use App\Http\Controllers\Controller;
use App\Http\Requests\Settings\PreferenceUpdateRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class PreferenceController extends Controller
{
    public function edit(Request $request): Response
    {
        $preference = $request->user()->preference;

        return Inertia::render('settings/Preferences', [
            'preference' => $preference ? [
                'dietary_restrictions' => $preference->dietary_restrictions,
                'style_preferences' => $preference->style_preferences,
                'other_notes' => $preference->other_notes,
            ] : null,
            'dietaryRestrictions' => collect(DietaryRestriction::cases())->map(fn (DietaryRestriction $r) => [
                'value' => $r->value,
                'label' => $r->label(),
            ]),
            'stylePreferences' => collect(StylePreference::cases())->map(fn (StylePreference $s) => [
                'value' => $s->value,
                'label' => $s->label(),
            ]),
        ]);
    }

    public function update(PreferenceUpdateRequest $request): RedirectResponse
    {
        $user = $request->user();
        $validated = $request->validated();

        $user->preference()->updateOrCreate(
            ['user_id' => $user->id],
            $validated,
        );

        Inertia::flash('toast', ['type' => 'success', 'message' => __('preferences.updated')]);

        return to_route('preferences.edit');
    }
}
