<?php
namespace Gestoreasy\Core\Fiscal\Nfse;

use Gestoreasy\Core\Fiscal\Nfse\Providers\RJProvider;
use Gestoreasy\Core\Fiscal\Nfse\Providers\DefaultProvider;

class ProviderFactory
{
    /**
     * Seleciona o provider com base na UF da empresa do tenant.
     *
     * @param \PDO $pdo
     * @return NfseProviderInterface
     */
    public static function forTenant(\PDO $pdo): NfseProviderInterface
    {
        $uf = 'RJ';
        try {
            $st = $pdo->query('SHOW COLUMNS FROM empresas LIKE "estado"');
            if ($st && $st->fetch()) {
                $r = $pdo->query('SELECT estado FROM empresas ORDER BY id ASC LIMIT 1')->fetch();
                $uf = strtoupper(trim((string)($r['estado'] ?? 'RJ')));
            } else {
                $r2 = $pdo->query('SELECT uf FROM empresas ORDER BY id ASC LIMIT 1')->fetch();
                $uf = strtoupper(trim((string)($r2['uf'] ?? 'RJ')));
            }
        } catch (\Throwable $e) {
            // Fallback para RJ
            $uf = 'RJ';
        }

        switch ($uf) {
            case 'RJ':
                return new RJProvider();
            default:
                return new DefaultProvider($uf);
        }
    }
}