<?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 UserDeleteController
{
    private UserModel $model;

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

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

        try {
            val::key('user_id', val::intType()->positive())
                ->assert($body);
        } catch (ValidationException $e) {
            return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
        }

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

        $deleted = $this->model->deleteUserById($userId, $companyId);

        return $deleted
            ? ResponseLib::sendOk(['deleted' => true])
            : ResponseLib::sendFail("User not found", [], "E_NOT_FOUND")->withStatus(204);
    }
}