<?php

namespace Controllers;

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

class RegisterController
{
    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('username', val::stringType()->notEmpty()->length(1, 100))
                ->key('email', val::email())
                ->key('password', val::stringType()->length(8, null))
                ->key('phone', val::stringType()->notEmpty()->length(1, 50))
                ->key('address', val::stringType()->notEmpty()->length(1, 255))
                ->key('city', val::stringType()->notEmpty()->length(1, 100))
                ->key('state', val::stringType()->notEmpty()->length(1, 100))
                ->key('zip', val::stringType()->notEmpty()->length(1, 20))
                ->key('country', val::stringType()->notEmpty()->length(1, 100))
                ->key('kyc', val::intType())
                ->key('birthdate', val::intType())
                ->key('cpf', val::stringType()->notEmpty()->length(1, 50))
                ->key('company_id', val::intType()->positive())
                ->key('role_id', val::intType()->positive())
                ->assert($body);
        } catch (ValidationException $e) {
            return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
        }

        $userData = $this->userModel->createUser($body);

        if (!$userData) {
            return ResponseLib::sendFail("Email already exists or creation failed", [], "E_VALIDATE")->withStatus(400);
        }

        return ResponseLib::sendOk($userData, "S_CREATED");
    }
}