from __future__ import annotations

import aiosqlite

MIGRATIONS = [
    # v1: initial schema
    """
    CREATE TABLE IF NOT EXISTS audit_entries (
        id TEXT PRIMARY KEY,
        timestamp TEXT NOT NULL,
        user_email TEXT,
        operation_type TEXT NOT NULL,
        object_type TEXT NOT NULL,
        object_id TEXT,
        params TEXT,
        status TEXT NOT NULL DEFAULT 'pending',
        result TEXT,
        error_message TEXT,
        rolled_back_at TEXT,
        rollback_audit_id TEXT
    );
    """,
    """
    CREATE TABLE IF NOT EXISTS rollback_states (
        id TEXT PRIMARY KEY,
        audit_id TEXT NOT NULL REFERENCES audit_entries(id),
        object_type TEXT NOT NULL,
        object_id TEXT,
        previous_state TEXT NOT NULL,
        created_at TEXT NOT NULL
    );
    """,
]


async def apply_migrations(db: aiosqlite.Connection) -> None:
    """Apply all migrations in order."""
    for sql in MIGRATIONS:
        await db.executescript(sql)
    await db.commit()
