"""
Миграция v1.14: создать таблицы events и event_participants для календаря событий
"""
import sqlite3
import asyncio

DB_PATH = 'database/domovoy.db'


async def migrate():
    """Создать таблицы events и event_participants"""
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()

    # Проверяем таблицу events
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='events'")
    if not cursor.fetchone():
        print("➕ Создаём таблицу events...")
        cursor.execute("""
            CREATE TABLE events (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                title TEXT NOT NULL,
                description TEXT,
                event_type TEXT DEFAULT 'general',
                event_date TIMESTAMP NOT NULL,
                location TEXT,
                created_by BIGINT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                is_active BOOLEAN DEFAULT 1,
                reminder_sent BOOLEAN DEFAULT 0,
                FOREIGN KEY (created_by) REFERENCES users(user_id)
            )
        """)
        cursor.execute("CREATE INDEX ix_events_date ON events(event_date)")
        cursor.execute("CREATE INDEX ix_events_type ON events(event_type)")
        cursor.execute("CREATE INDEX ix_events_active ON events(is_active)")
        print("✅ Таблица events создана")
    else:
        print("ℹ️ Таблица events уже существует")

    # Проверяем таблицу event_participants
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='event_participants'")
    if not cursor.fetchone():
        print("➕ Создаём таблицу event_participants...")
        cursor.execute("""
            CREATE TABLE event_participants (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                event_id INTEGER NOT NULL,
                user_id BIGINT NOT NULL,
                joined_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (event_id) REFERENCES events(id),
                FOREIGN KEY (user_id) REFERENCES users(user_id)
            )
        """)
        cursor.execute("CREATE INDEX ix_event_participants_event ON event_participants(event_id)")
        cursor.execute("CREATE INDEX ix_event_participants_user ON event_participants(user_id)")
        cursor.execute("CREATE UNIQUE INDEX ix_event_participants_unique ON event_participants(event_id, user_id)")
        print("✅ Таблица event_participants создана")
    else:
        print("ℹ️ Таблица event_participants уже существует")

    conn.commit()
    conn.close()
    print("✅ Миграция v1.14 завершена!")


if __name__ == '__main__':
    asyncio.run(migrate())
