#!/usr/bin/env php
<?php
/**
 * Migration 018 — encrypt the existing plaintext SMTP password at rest.
 *
 * Usage: php app/migrations/pending/018_encrypt_smtp_password.php [DB_PATH]
 *
 * Reads APP_KEY from app/.env, encrypts the current smtp_settings.password
 * using AES-256-GCM, and writes it back.
 * Safe to re-run: Crypto::isEncrypted() is checked before encrypting.
 */

$root   = dirname(__DIR__, 2); // app/
$dbPath = $argv[1] ?? ($root . '/storage/xamxam.db');

if (!file_exists($dbPath)) {
    die("Database not found: $dbPath\n");
}

define('APP_ROOT', $root);
require_once $root . '/src/Crypto.php';

$pdo = new PDO('sqlite:' . $dbPath);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$row = $pdo->query("SELECT password FROM smtp_settings WHERE id = 1")->fetch(PDO::FETCH_ASSOC);

if (!$row) {
    echo "No smtp_settings row found — nothing to do.\n";
    exit(0);
}

$current = $row['password'];

if (Crypto::isEncrypted($current)) {
    echo "Password already encrypted — nothing to do.\n";
    exit(0);
}

if ($current === '') {
    echo "Password is empty — nothing to do.\n";
    exit(0);
}

$encrypted = Crypto::encrypt($current);
$pdo->prepare("UPDATE smtp_settings SET password = ? WHERE id = 1")->execute([$encrypted]);

echo "SMTP password encrypted successfully.\n";
