<?php

declare(strict_types=1);

namespace App\Core;

use App\Services\SaasAccessService;

class Tenant
{
    public static function companyId(): ?int
    {
        $id = Session::get('company_id');
        return $id !== null ? (int) $id : null;
    }

    public static function setCompanyId(?int $companyId): void
    {
        if ($companyId === null) {
            Session::forget('company_id');
            return;
        }

        Session::put('company_id', (int) $companyId);
    }

    public static function ensure(): bool
    {
        $companyId = self::companyId();
        if ($companyId === null || $companyId <= 0) {
            Session::put('tenant_block_reason', 'Debes seleccionar una empresa antes de continuar.');
            return false;
        }

        try {
            $stmt = Database::connection()->prepare(
                'SELECT id FROM empresas WHERE id = :id LIMIT 1'
            );
            $stmt->execute([':id' => $companyId]);

            $exists = (bool) $stmt->fetchColumn();
            if (!$exists) {
                self::setCompanyId(null);
                Session::put('tenant_block_reason', 'La empresa seleccionada no existe.');
            }

            if (!$exists) {
                return false;
            }

            if (Auth::isSuperadmin()) {
                Session::forget('tenant_block_reason');
                return true;
            }

            $access = (new SaasAccessService())->evaluateCompanyAccess((int) $companyId, true);
            if (!(bool) ($access['allowed'] ?? false)) {
                self::setCompanyId(null);
                Session::put(
                    'tenant_block_reason',
                    (string) ($access['message'] ?? 'La empresa no se encuentra habilitada para operar.')
                );
                return false;
            }

            Session::forget('tenant_block_reason');
            return $exists;
        } catch (\Throwable) {
            Session::put('tenant_block_reason', 'No fue posible validar el acceso a la empresa activa.');
            return false;
        }
    }
}
