<?php
/**
 * Phase 2 Migration: AI Pre-Audit & Duplicate Prevention
 * Run: php scripts/migrate_phase2.php
 */

require_once __DIR__ . '/../app/bootstrap/init.php';

use App\Core\Database;

$db = Database::getInstance();

echo "═══════════════════════════════════════════\n";
echo "  مُصادَق — Phase 2 Migration\n";
echo "  AI Pre-Audit & Duplicate Prevention\n";
echo "═══════════════════════════════════════════\n\n";

$migrations = [

    // 1. Add invoice_hash for duplicate prevention
    'add_invoice_hash' => "ALTER TABLE invoices ADD COLUMN invoice_hash VARCHAR(64) NULL",

    // 2. Add validation_warnings for AI Pre-Audit
    'add_validation_warnings' => "ALTER TABLE invoices ADD COLUMN validation_warnings JSON NULL",

    // 2.5 Add deleted_at for soft delete (Missing in Phase 1 for this table)
    'add_invoices_soft_delete' => "ALTER TABLE invoices ADD COLUMN deleted_at DATETIME NULL DEFAULT NULL",

    // 3. Create Unique Index to prevent duplicates within the same tenant & company
    // Using a regular index for now, application logic will handle uniqueness to allow nulls
    'add_hash_index' => "CREATE INDEX idx_invoice_hash ON invoices(tenant_id, company_id, invoice_hash)",
];

$success = 0;
$skipped = 0;
$failed  = 0;

foreach ($migrations as $name => $sql) {
    try {
        $db->exec($sql);
        echo "  ✅ {$name}\n";
        $success++;
    } catch (\PDOException $e) {
        $msg = $e->getMessage();
        // Ignore "duplicate column" (1060), "duplicate key name" (1061), or "already exists" errors
        if (str_contains($msg, 'Duplicate column') || str_contains($msg, 'Duplicate key name') || str_contains($msg, 'already exists')) {
            echo "  ⏭️  {$name} (already exists)\n";
            $skipped++;
        } else {
            echo "  ❌ {$name}: {$msg}\n";
            $failed++;
        }
    }
}

echo "\n═══════════════════════════════════════════\n";
echo "  Migration Complete!\n";
echo "  ✅ Success: {$success} | ⏭️ Skipped: {$skipped} | ❌ Failed: {$failed}\n";
echo "═══════════════════════════════════════════\n";
