<?php

namespace Controllers;

use Firebase\JWT\JWT;
use Libs\ResponseLib;
use Models\UserModel;
use Psr\Http\Message\ServerRequestInterface;
use Respect\Validation\Validator as val;
use Respect\Validation\Exceptions\ValidationException;

class LoginController
{
    private UserModel $userModel;

    public function __construct()
    {
        $this->userModel = new UserModel();
    }

    public function __invoke(ServerRequestInterface $request)
    {
        $body = json_decode((string) $request->getBody(), true) ?? [];

        try {
            val::key('email', val::email())
                ->key('password', val::stringType()->notEmpty()->length(8, null))
                ->assert($body);
        } catch (ValidationException $e) {
            return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(401);
        }

        $email = $body['email'];
        $password = $body['password'];

        $user = $this->userModel->validateLogin($email, $password);

        if (!$user) {
            return ResponseLib::sendFail("Invalid credentials", [], "E_VALIDATE")->withStatus(401);
        }

        $payload = [
            'sub' => $user['user_id'],
            'email' => $user['user_email'],
            'iat' => time(),
            'exp' => time() + 3600
        ];
        $jwt = JWT::encode($payload, $_ENV['JWT_SECRET'], 'HS256');

        return ResponseLib::sendOk(['token' => $jwt, 'user_id' => $user['user_id'], 'company_id' => $user['company_id']]);
    }
}