<?php

declare(strict_types=1);

/**
 * Crea tablas de organización (companies, branches, user_access) y datos demo.
 * Ejecutar: php bin/db-seed-organization.php
 */

require_once dirname(__DIR__) . '/config/bootstrap.php';

use ApiModel\Infrastructure\Persistence\Database;

$sqlFile = dirname(__DIR__) . '/docs/db_seed_organization.sql';

echo "=== SEED ORGANIZACIÓN (empresas / sucursales) ===\n";

if (! is_file($sqlFile)) {
    fwrite(STDERR, "No se encontró: {$sqlFile}\n");
    exit(1);
}

try {
    $pdo = Database::connect();
    $driver = $pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
    echo 'Conectado (' . $driver . ").\n";

    $sql = file_get_contents($sqlFile);
    if ($sql === false) {
        throw new RuntimeException('No se pudo leer el archivo SQL');
    }

    if ($driver === 'sqlite') {
        $sql = str_replace('auth.', '', $sql);
        $sql = str_replace('DEFAULT gen_random_uuid()', '', $sql);
        $sql = str_replace('BOOLEAN', 'INTEGER', $sql);
        $sql = str_replace('TIMESTAMP', 'TEXT', $sql);
        $sql = str_replace('TRUE', '1', $sql);
        $sql = str_replace('FALSE', '0', $sql);
        $sql = str_replace('CURRENT_TIMESTAMP', "datetime('now')", $sql);
    }

    $pdo->exec($sql);

    $count = $pdo->query('SELECT COUNT(*) FROM companies')->fetchColumn();
    echo "Tabla companies OK. Registros: {$count}\n";
    echo "=== COMPLETADO ===\n";
} catch (Throwable $e) {
    fwrite(STDERR, 'ERROR: ' . $e->getMessage() . "\n");
    exit(1);
}
