<?php

namespace App\Http\Controllers\Api\Ui;

use App\Http\Controllers\Api\Core\BaseApiController;
use App\Http\Requests\Ui\UiStyleRequest;
use App\Http\Resources\Ui\UiStyleResource;
use App\Services\Ui\UiStyleService;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class UiController extends BaseApiController
{
    public function __construct(private UiStyleService $styleService)
    {
        parent::__construct();
    }

    public function style(UiStyleRequest $request): JsonResponse
    {
        $guard = $this->authenticatedUserIdOrUnauthorized();
        if ($guard instanceof JsonResponse) {
            return $guard;
        }

        $prefs = $this->styleService->update($guard, $request->validated());

        return $this->success([
            'preferences' => new UiStyleResource($prefs),
        ], 'Style updated.');
    }

    /**
     * @return int|JsonResponse
     */
    private function authenticatedUserIdOrUnauthorized(): int|JsonResponse
    {
        $userId = (int) (auth()->id() ?? 0);
        if ($userId <= 0) {
            return $this->error('Unauthorized.', Response::HTTP_UNAUTHORIZED);
        }

        return $userId;
    }
}
