<?php

declare(strict_types=1);

namespace App\Service;

use App\Repository\UserRepository;
use Firebase\JWT\JWT;

final class UserService
{
    private UserRepository $UserRepository;

    public function __construct(UserRepository $UserRepository)
    {
        $this->UserRepository = $UserRepository;
    }

    public function checkAndGet(int $UserId): object
    {
        return $this->UserRepository->checkAndGet($UserId);
    }

    public function getAll(): array
    {
        return $this->UserRepository->getAll();
    }

    public function getOne(int $UserId): object
    {
        return $this->checkAndGet($UserId);
    }

    public function create(array $input): object
    {
        $user = json_decode((string) json_encode($input), false);
        $hash = password_hash($user->password, PASSWORD_BCRYPT);
        $user->password = $hash;
//         $User = json_decode((string) json_encode($input), false);
        $User = json_decode((string) json_encode($user), false);

        return $this->UserRepository->create($User);
    }

    public function update(array $input, int $UserId): object
    {
        $User = $this->checkAndGet($UserId);
      
        $user = json_decode((string) json_encode($input), false);
        $hash = password_hash($user->password, PASSWORD_BCRYPT);
        $user->password = $hash;
//         $data = json_decode((string) json_encode($input), false);
        $data = json_decode((string) json_encode($user), false);

        return $this->UserRepository->update($User, $data);
    }

    public function delete(int $UserId): void
    {
        $this->checkAndGet($UserId);
        $this->UserRepository->delete($UserId);
    }
    
    public function login(array $input): array
    {
        $User = json_decode((string) json_encode($input), false);
      
        $user = $this->UserRepository->login($User);

        $tokenData = [
            'sub' => $user->id,
            'email' => $user->email,
            'name' => $user->name,
            'iat' => time(),
            'exp' => time() + (60 * 60),
            'kid' => 'v3SEla87Dh911cIb5teT4', // Asignación del "kid" aquí
        ];

        $token = JWT::encode($tokenData, getenv('SECRET_KEY'), 'HS256');


//          `User` (`id`, `fecha`, `name`, `email`, `password`, `field1`, `field2`, `field3`, `field4`, `field5`)
        return [
            'token' => $token,
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'field1' => $user->field1,
            'field2' => $user->field2,
            'field3' => $user->field3,
            'field4' => $user->field4,
            'field5' => $user->field5,
        ];
    }
}
