"""
Add pos_session_timeout_minutes to app_settings and align ERP idle defaults.

Run: python migrations/add_pos_session_timeout.py
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from sqlalchemy import text
from app.core.database import engine
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def column_exists(conn, table: str, column: str) -> bool:
    bind = engine.url.drivername
    if "sqlite" in bind:
        rows = conn.execute(text(f"PRAGMA table_info({table})")).fetchall()
        return any(r[1] == column for r in rows)
    result = conn.execute(
        text(
            "SELECT 1 FROM information_schema.columns "
            "WHERE table_name = :t AND column_name = :c"
        ),
        {"t": table, "c": column},
    )
    return result.fetchone() is not None


def run_migration():
    with engine.begin() as conn:
        if not column_exists(conn, "app_settings", "pos_session_timeout_minutes"):
            logger.info("Adding app_settings.pos_session_timeout_minutes …")
            conn.execute(
                text(
                    "ALTER TABLE app_settings "
                    "ADD COLUMN pos_session_timeout_minutes INTEGER DEFAULT 1"
                )
            )
        else:
            logger.info("pos_session_timeout_minutes already exists — skipping")

        conn.execute(
            text(
                "UPDATE app_settings SET session_timeout_minutes = 3 "
                "WHERE session_timeout_minutes IS NULL"
            )
        )
        conn.execute(
            text(
                "UPDATE app_settings SET session_timeout = session_timeout_minutes "
                "WHERE session_timeout IS NULL"
            )
        )
        conn.execute(
            text(
                "UPDATE app_settings SET pos_session_timeout_minutes = 1 "
                "WHERE pos_session_timeout_minutes IS NULL"
            )
        )
    logger.info("Session timeout migration complete.")


if __name__ == "__main__":
    run_migration()
