<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\UserPreferenceRequest;
use App\Http\Resources\UserPreferenceResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

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

        if (! $preference) {
            return response()->json(['data' => null]);
        }

        return response()->json(['data' => new UserPreferenceResource($preference)]);
    }

    public function update(UserPreferenceRequest $request): JsonResponse
    {
        $preference = $request->user()->preference()->updateOrCreate(
            ['user_id' => $request->user()->id],
            $request->validated(),
        );

        return response()->json(['data' => new UserPreferenceResource($preference)]);
    }
}
