"""Migration 003: Add sync outbox and conflict audit tables.

The outbox ensures crash-safe sync delivery (at-least-once semantics).
The conflict audit log records every conflict resolution for debugging.
"""
from . import register


@register(3, "Add sync outbox and conflict audit tables")
def migrate(db) -> None:
    """Create _sync_outbox and _conflict_audit tables."""

    # Sync outbox: crash-safe pending sync queue
    db.execute("""
        CREATE TABLE IF NOT EXISTS _sync_outbox (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            table_name TEXT NOT NULL,
            row_id TEXT NOT NULL,
            operation TEXT NOT NULL DEFAULT 'upsert',
            created_at TEXT DEFAULT (datetime('now')),
            delivered_at TEXT DEFAULT NULL,
            attempts INTEGER DEFAULT 0,
            last_error TEXT DEFAULT NULL
        )
    """)
    db.execute(
        "CREATE INDEX IF NOT EXISTS idx_outbox_pending "
        "ON _sync_outbox(delivered_at) WHERE delivered_at IS NULL"
    )

    # Conflict audit log: records every conflict resolution
    db.execute("""
        CREATE TABLE IF NOT EXISTS _conflict_audit (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            table_name TEXT NOT NULL,
            row_id TEXT NOT NULL,
            strategy TEXT NOT NULL,
            local_version INTEGER,
            remote_version INTEGER,
            local_node TEXT,
            remote_node TEXT,
            resolved_to TEXT NOT NULL,
            merged_fields TEXT DEFAULT '',
            created_at TEXT DEFAULT (datetime('now'))
        )
    """)
    db.execute(
        "CREATE INDEX IF NOT EXISTS idx_conflict_audit_table "
        "ON _conflict_audit(table_name, created_at)"
    )
