<?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) ?? [];

        $companyId = (int)($request->getAttribute('api_company_id') ?? 0);
        if ($companyId <= 0) {
            return ResponseLib::sendFail('Authenticated company not found', [], 'E_VALIDATE')->withStatus(401);
        }

        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('birthdate', val::intType())
                ->key('cpf', val::stringType()->notEmpty()->length(1, 50))
                ->assert($body);
        } catch (ValidationException $e) {
            return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
        }

        $body['company_id'] = $companyId;

        $body['kyc'] = 0;
        $body['role_id'] = 2;

        if ($this->userModel->isEmailActive((string)$body['email'])) {
            return ResponseLib::sendFail("Email already in use", [], "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");
    }
}