# app/src/storage/schema.py

from __future__ import annotations

from psycopg import sql

from src.storage.session import get_connection


# SQL-команды для первичной инициализации базы данных.
DDL: list[sql.SQL] = [
    sql.SQL("""
    CREATE TABLE IF NOT EXISTS balance_snapshots (
        id BIGSERIAL PRIMARY KEY,
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        source TEXT NOT NULL,
        payload_json JSONB NOT NULL
    )
    """),
    sql.SQL("""
    CREATE TABLE IF NOT EXISTS journal_events (
        id BIGSERIAL PRIMARY KEY,
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        level TEXT NOT NULL,
        event_type TEXT NOT NULL,
        message TEXT NOT NULL,
        payload_json JSONB
    )
    """),
    sql.SQL("""
    CREATE INDEX IF NOT EXISTS idx_journal_events_created_at
    ON journal_events (created_at DESC)
    """),
    sql.SQL("""
    CREATE INDEX IF NOT EXISTS idx_journal_events_event_type
    ON journal_events (event_type)
    """),
]


# создаёт таблицы и индексы, если они ещё не существуют
def init_schema() -> None:
    with get_connection() as connection:
        with connection.cursor() as cursor:
            for statement in DDL:
                cursor.execute(statement)