<?php

namespace App\Http\Controllers\Api\Frontend;

use App\Http\Controllers\Api\Core\BaseApiController;
use App\Http\Resources\Frontend\ProfileIconResource;
use App\Services\Frontend\ProfileIconService;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class InfoIconController extends BaseApiController
{
    public function __construct(private ProfileIconService $service)
    {
        parent::__construct();
    }

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

        $payload = $this->service->buildForUser($guard);

        return $this->success([
            'profile' => new ProfileIconResource($payload),
        ]);
    }

    /**
     * @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;
    }
}
