from __future__ import annotations

import sqlite3

from backend.database.migrations.runner import Migration


def create_account_switch_grants(connection: sqlite3.Connection) -> None:
    connection.execute(
        """
        CREATE TABLE IF NOT EXISTS account_switch_grants (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            device_hash TEXT NOT NULL,
            user_id INTEGER NOT NULL,
            granted_at TEXT NOT NULL,
            last_used_at TEXT NOT NULL,
            expires_at TEXT NOT NULL,
            UNIQUE (device_hash, user_id),
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        )
        """
    )
    connection.execute(
        """
        CREATE INDEX IF NOT EXISTS idx_account_switch_grants_device
        ON account_switch_grants(device_hash, last_used_at DESC)
        """
    )
    connection.execute(
        """
        CREATE INDEX IF NOT EXISTS idx_account_switch_grants_expiry
        ON account_switch_grants(expires_at)
        """
    )


MIGRATION = Migration(
    version="0005",
    name="create_account_switch_grants",
    action=create_account_switch_grants,
    signature="account-switch-grants:v1:device,user,granted,used,expires,unique",
)
