<?php

declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    http_response_code(404);
    exit;
}

require_once dirname(__DIR__) . '/config.php';
require_once dirname(__DIR__) . '/lib/CryptoService.php';
require_once dirname(__DIR__) . '/lib/ImapProviderCatalog.php';

$apply = in_array('--apply', $argv, true);
$rows = $pdo->query(
    'SELECT id, id_admin, imap_clave, plataforma, nombre_proveedor, imap_host
     FROM configuraciones_imap ORDER BY id'
)->fetchAll(PDO::FETCH_ASSOC);

$stats = ['v2' => 0, 'migratable' => 0, 'migrated' => 0, 'failed' => 0, 'microsoft' => 0];

foreach ($rows as $row) {
    $id = (int) $row['id'];
    if (ImapProviderCatalog::isMicrosoftProvider(
        (string) ($row['plataforma'] ?? $row['nombre_proveedor'] ?? ''),
        (string) ($row['imap_host'] ?? '')
    )) {
        $stats['microsoft']++;
        fwrite(STDOUT, "[REVISAR] buzón ID {$id}: proveedor Microsoft heredado.\n");
    }

    $stored = (string) $row['imap_clave'];
    if (!CryptoService::needsMigration($stored)) {
        $stats['v2']++;
        continue;
    }

    $plain = CryptoService::decrypt($stored);
    if ($plain === null || $plain === '') {
        $stats['failed']++;
        fwrite(STDERR, "[ERROR] buzón ID {$id}: no se pudo leer el cifrado antiguo.\n");
        continue;
    }

    $stats['migratable']++;
    if (!$apply) {
        fwrite(STDOUT, "[SIMULACIÓN] buzón ID {$id}: puede migrarse a v2.\n");
        continue;
    }

    $newValue = CryptoService::encrypt($plain);
    $stmt = $pdo->prepare('UPDATE configuraciones_imap SET imap_clave = ? WHERE id = ? AND imap_clave = ?');
    $stmt->execute([$newValue, $id, $stored]);
    if ($stmt->rowCount() === 1) {
        $stats['migrated']++;
        fwrite(STDOUT, "[OK] buzón ID {$id}: migrado.\n");
    } else {
        $stats['failed']++;
        fwrite(STDERR, "[ERROR] buzón ID {$id}: el registro cambió durante la migración.\n");
    }
}

fwrite(STDOUT, "\nResumen:\n");
foreach ($stats as $name => $value) {
    fwrite(STDOUT, sprintf("- %-12s %d\n", $name . ':', $value));
}

if (!$apply) {
    fwrite(STDOUT, "\nNo se modificó la base de datos. Ejecuta nuevamente con --apply después de revisar el resultado.\n");
}
