"""銀行明細テーブルのマイグレーション"""
import os
from psycopg import connect


def create_bank_statement_table():
    conn = connect(
        host=os.getenv("DB_HOST"),
        port=int(os.getenv("DB_PORT", 5432)),
        dbname=os.getenv("DB_NAME"),
        user=os.getenv("DB_USER"),
        password=os.getenv("DB_PASSWORD"),
    )
    with conn.cursor() as cur:
        cur.execute("""
            CREATE TABLE IF NOT EXISTS bank_statement_rows (
                id              SERIAL PRIMARY KEY,
                tx_date         DATE        NOT NULL,
                description     TEXT        NOT NULL DEFAULT '',
                debit           BIGINT      NOT NULL DEFAULT 0,
                credit          BIGINT      NOT NULL DEFAULT 0,
                balance         BIGINT,
                memo            TEXT        NOT NULL DEFAULT '',
                bank_name       TEXT        NOT NULL DEFAULT '',
                import_batch_id TEXT        NOT NULL,
                row_hash        TEXT        NOT NULL,
                imported_at     TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                CONSTRAINT uq_bank_stmt_hash UNIQUE (row_hash)
            )
        """)
        cur.execute("""
            CREATE INDEX IF NOT EXISTS idx_bank_stmt_date
                ON bank_statement_rows (tx_date)
        """)
        cur.execute("""
            CREATE INDEX IF NOT EXISTS idx_bank_stmt_batch
                ON bank_statement_rows (import_batch_id)
        """)
        conn.commit()
        print("✓ bank_statement_rows テーブル確認完了")
    conn.close()
