<?php
/**
 * Migrație: redenumire emag_accounts.api_key → password
 * + adăugare coloană platform (per docs v4.5.1 — eMAG suportă 5 platforme).
 *
 * SQLite acceptă ALTER TABLE RENAME COLUMN din 3.25+ (default în XAMPP modern).
 * Pentru compatibilitate maximă, recreez tabelul (pattern oficial recomandat de SQLite).
 */
return function (PDO $db): void {

    // 1. Tabel nou cu schema corectă
    $db->exec("
        CREATE TABLE emag_accounts_new (
            id           INTEGER PRIMARY KEY AUTOINCREMENT,
            account_name TEXT    NOT NULL,
            username     TEXT    NOT NULL UNIQUE,
            password     TEXT    NOT NULL,
            platform     TEXT    NOT NULL DEFAULT 'ro'
                          CHECK(platform IN ('ro','bg','hu','fd_ro','fd_bg')),
            is_active    INTEGER NOT NULL DEFAULT 1,
            last_sync_at TEXT    NULL,
            created_at   TEXT    NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at   TEXT    NOT NULL DEFAULT CURRENT_TIMESTAMP
        )
    ");

    // 2. Copiez datele existente (api_key → password)
    $db->exec("
        INSERT INTO emag_accounts_new (id, account_name, username, password, platform, is_active, last_sync_at, created_at, updated_at)
        SELECT id, account_name, username, api_key, 'ro', is_active, last_sync_at, created_at, updated_at
        FROM emag_accounts
    ");

    // 3. Schimbă tabelele
    $db->exec("DROP TABLE emag_accounts");
    $db->exec("ALTER TABLE emag_accounts_new RENAME TO emag_accounts");

    // 4. Refac indexul + trigger-ul
    $db->exec("CREATE INDEX idx_accounts_active ON emag_accounts(is_active)");
    $db->exec("
        CREATE TRIGGER trg_emag_accounts_updated
        AFTER UPDATE ON emag_accounts
        FOR EACH ROW
        BEGIN
            UPDATE emag_accounts SET updated_at = CURRENT_TIMESTAMP WHERE id = OLD.id;
        END
    ");
};
