<?php

namespace src\Controller;

use src\Service\autenticacaoService;
use src\Service\permissaoService;
use src\Utils\responseHelpers;
use src\Utils\validator;
use src\Utils\token;
use src\Model\autenticacaoModel;
use Exception;

class autenticacaoController
{

    private $autenticacaoService;
    private $permissaoService;

    public function __construct(autenticacaoService $autenticacaoService, permissaoService $permissaoService)
    {
        $this->autenticacaoService = $autenticacaoService;
        $this->permissaoService = $permissaoService;
    }

    public function autenticacao()
    {
        try {
            $data = json_decode(file_get_contents('php://input'), true);
            validator::validateRequiredFields($data, ['email', 'senha']);
            $data = array_map('htmlspecialchars', $data);

            $autenticacaoModel = new autenticacaoModel();
            $autenticacaoModel->setEmail($data['email']);
            $autenticacaoModel->setSenha(md5(md5($data['senha'])));

            $usuario = $this->autenticacaoService->autenticacao($autenticacaoModel);

            if ($usuario) {

                $permissao = $this->permissaoService->listar($usuario->id);

                $token = token::createToken([
                    'id' => $usuario->id,
                    'email' => $usuario->email,
                    'nome' => $usuario->nome,
                    'permissao' => $permissao,
                    'exp' => time() + (60 * 60)
                ]);

                responseHelpers::sendSuccessResponse(['token' => $token]);
            } else {
                responseHelpers::sendErrorResponse('Usuário ou senha inválidos', 401);
            }
        } catch (Exception $e) {
            responseHelpers::sendErrorResponse($e->getMessage(), 500);
        }
    }
}
