<?php

declare(strict_types=1);

namespace ApiModel\Action;

use ApiModel\Service\UserService;
use ApiModel\Shared\Support\AuthContext;
use ApiModel\Shared\Exceptions\BadRequestException;
use ApiModel\Shared\Http\HttpUtil;
use Psr\Http\Message\ServerRequestInterface;

final class UserAction
{
    public function __construct(private readonly UserService $users) {}

    /** @return array<string, mixed> */
    public function me(ServerRequestInterface $request): array
    {
        $u = AuthContext::jwtUser($request);

        return $this->users->me($u['userId']);
    }

    /** @return array<string, mixed> */
    public function updateLanguage(ServerRequestInterface $request): array
    {
        $u = AuthContext::jwtUser($request);
        $b = HttpUtil::parseJson($request);
        $lang = (string) ($b['language'] ?? '');
        if (! in_array($lang, ['es', 'en', 'nl'], true)) {
            throw new BadRequestException('Idioma inválido');
        }

        return $this->users->updateMyLanguage($u['userId'], $lang);
    }

    /** @return array<string, mixed> */
    public function updatePhoto(ServerRequestInterface $request): array
    {
        $u = AuthContext::jwtUser($request);
        $b = HttpUtil::parseJson($request);
        $photo = array_key_exists('photo', $b) ? $b['photo'] : null;
        if ($photo !== null && ! is_string($photo)) {
            throw new BadRequestException('Foto inválida');
        }

        return $this->users->updateMyPhoto($u['userId'], $photo);
    }
}
