<?php
/**
 * Remove all row data while keeping table structures (prepare for live / fresh start).
 */

require_once __DIR__ . '/db-table-stats.php';

/**
 * Tables whose rows are kept by default (accounts + app configuration).
 *
 * @return list<string>
 */
function nazareth_db_clean_preserve_tables(): array
{
    return ['users', 'settings'];
}

/**
 * Truncate all base tables except preserved names. Structures and indexes unchanged.
 *
 * @param list<string> $preserveTables
 * @return array{truncated: list<string>, preserved: list<string>, skipped: list<string>}
 */
function nazareth_clean_database_data(PDO $pdo, array $preserveTables = null): array
{
    if ($preserveTables === null) {
        $preserveTables = nazareth_db_clean_preserve_tables();
    }

    $preserve = array_map('strtolower', $preserveTables);
    $tables = nazarethListBaseTablesWithStats($pdo);
    $truncated = [];
    $preserved = [];
    $skipped = [];

    $pdo->exec('SET FOREIGN_KEY_CHECKS = 0');

    foreach ($tables as $table) {
        $name = $table['name'];
        if (in_array(strtolower($name), $preserve, true)) {
            $preserved[] = $name;
            continue;
        }
        try {
            $safe = str_replace('`', '', $name);
            $pdo->exec('TRUNCATE TABLE `' . $safe . '`');
            $truncated[] = $name;
        } catch (PDOException $e) {
            $skipped[] = $name . ': ' . $e->getMessage();
        }
    }

    $pdo->exec('SET FOREIGN_KEY_CHECKS = 1');

    return [
        'truncated' => $truncated,
        'preserved' => $preserved,
        'skipped' => $skipped,
    ];
}
