<?php

declare(strict_types=1);

use Dotenv\Dotenv;
use App\Core\Database;

require_once dirname(__DIR__) . '/vendor/autoload.php';

$basePath = dirname(__DIR__);

if (file_exists($basePath . '/.env')) {
    Dotenv::createImmutable($basePath)->safeLoad();
}

$fresh = in_array('--fresh', $argv, true);
$dataPath = $basePath . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'data';

if (!is_dir($dataPath)) {
    fwrite(STDERR, "Pasta storage/data nao encontrada.\n");
    exit(1);
}

$_ENV['DB_CONNECTION'] = 'mysql';
Database::ensureSchema();
$pdo = Database::pdo();

if ($fresh) {
    $pdo->exec('TRUNCATE TABLE app_records');
    echo "Tabela app_records limpa.\n";
}

$statement = $pdo->prepare(
    'INSERT INTO app_records (collection, record_id, payload)
     VALUES (:collection, :record_id, :payload)
     ON DUPLICATE KEY UPDATE payload = VALUES(payload), updated_at = CURRENT_TIMESTAMP'
);

$total = 0;
$files = glob($dataPath . DIRECTORY_SEPARATOR . '*.json') ?: [];

foreach ($files as $file) {
    $collection = pathinfo($file, PATHINFO_FILENAME);
    $records = json_decode((string) file_get_contents($file), true);

    if (!is_array($records)) {
        echo "Ignorado {$collection}: JSON invalido.\n";
        continue;
    }

    $count = 0;
    foreach (array_values($records) as $index => $record) {
        if (!is_array($record)) {
            continue;
        }

        $recordId = (int) ($record['id'] ?? ($index + 1));
        if ($recordId <= 0) {
            $recordId = $index + 1;
        }

        $record['id'] = $recordId;
        $statement->execute([
            'collection' => $collection,
            'record_id' => $recordId,
            'payload' => json_encode($record, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        ]);

        $count++;
    }

    $total += $count;
    echo "Importado {$collection}: {$count} registo(s).\n";
}

echo "Concluido. Total importado/actualizado: {$total} registo(s).\n";
