from __future__ import annotations

import sqlite3

from backend.database.migrations.runner import Migration


def upgrade(connection: sqlite3.Connection) -> None:
    connection.execute(
        """
        CREATE TABLE market_insight_snapshots (
            kind TEXT NOT NULL CHECK (
                kind IN ('auction', 'themes', 'popularity', 'dragon-list')
            ),
            trade_date TEXT NOT NULL,
            entity_key TEXT NOT NULL DEFAULT '',
            observed_at TEXT NOT NULL,
            state TEXT NOT NULL CHECK (state IN ('realtime', 'final', 'archive')),
            source TEXT NOT NULL,
            coverage REAL NOT NULL CHECK (coverage >= 0 AND coverage <= 1),
            payload_json TEXT NOT NULL,
            PRIMARY KEY (kind, trade_date, entity_key)
        )
        """
    )
    connection.execute(
        """
        CREATE TABLE seat_aliases (
            seat_name TEXT PRIMARY KEY,
            alias_name TEXT NOT NULL,
            updated_at TEXT NOT NULL,
            updated_by INTEGER REFERENCES users(id) ON DELETE SET NULL
        )
        """
    )


def downgrade(connection: sqlite3.Connection) -> None:
    connection.execute("DROP TABLE seat_aliases")
    connection.execute("DROP TABLE market_insight_snapshots")


MIGRATION = Migration(
    version=5,
    name="create_market_insight_archives",
    signature="market:v3:auction-themes-popularity-dragon-list",
    upgrade=upgrade,
    downgrade=downgrade,
)
