<?php

declare(strict_types=1);

require dirname(__DIR__) . '/bootstrap.php';

use Core\Database;

if (!in_array('--force', $argv, true)) {
    echo "Este script remove a massa fake de homologação. Rode com --force para continuar.\n";
    exit(1);
}

$pdo = Database::connection();
$pdo->beginTransaction();

try {
    $st = $pdo->prepare("SELECT id FROM admissions WHERE personal_email LIKE :email OR full_name LIKE :name");
    $st->execute([
        'email' => '%@homolog.local',
        'name' => 'Teste Homologação%',
    ]);

    $ids = array_map('intval', array_column($st->fetchAll(), 'id'));

    if ($ids !== []) {
        $in = implode(',', array_fill(0, count($ids), '?'));
        $files = $pdo->prepare("SELECT relative_path FROM attachments WHERE admission_id IN ($in)");
        $files->execute($ids);
        foreach ($files->fetchAll() as $file) {
            $absolute = dirname(__DIR__) . '/storage/' . $file['relative_path'];
            if (is_file($absolute)) {
                @unlink($absolute);
            }
        }

        $delete = $pdo->prepare("DELETE FROM admissions WHERE id IN ($in)");
        $delete->execute($ids);
    }

    $pdo->commit();
    echo "Massa fake removida com sucesso.\n";
} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    fwrite(STDERR, 'Falha ao limpar massa fake: ' . $e->getMessage() . "\n");
    exit(1);
}
