"""
Миграция: Добавить таблицу scheduled_posts для отложенной публикации
"""
import sqlite3

DB_PATH = 'database/domovoy.db'


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

    # Проверяем таблицу
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='scheduled_posts'")
    if not cursor.fetchone():
        print("➕ Создаём таблицу scheduled_posts...")
        cursor.execute("""
            CREATE TABLE scheduled_posts (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                text TEXT NOT NULL,
                photo_file_id TEXT,
                topic_id BIGINT,
                topic_name TEXT,
                recipients TEXT DEFAULT 'chat_only',
                scheduled_time TIMESTAMP NOT NULL,
                status TEXT DEFAULT 'pending',
                created_by BIGINT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                sent_at TIMESTAMP,
                error_message TEXT,
                message_id BIGINT,
                FOREIGN KEY (created_by) REFERENCES users(user_id)
            )
        """)
        cursor.execute("CREATE INDEX ix_scheduled_posts_time ON scheduled_posts(scheduled_time)")
        cursor.execute("CREATE INDEX ix_scheduled_posts_status ON scheduled_posts(status)")
        cursor.execute("CREATE INDEX ix_scheduled_posts_topic ON scheduled_posts(topic_name)")
        conn.commit()
        print("✅ Таблица scheduled_posts создана")
    else:
        print("ℹ️ Таблица scheduled_posts уже существует")

    conn.close()


if __name__ == '__main__':
    migrate()
