import os
import mysql.connector
from mysql.connector import Error

# DB Configuration (env preferred)
DB_CONFIG = {
    "host": os.environ.get("DB_HOST", "officialsite.kr"),
    "port": int(os.environ.get("DB_PORT", "23306")),
    "user": os.environ.get("DB_USER", "admin"),
    "password": os.environ.get("DB_PASSWORD", "dlgks~123"),
    "database": os.environ.get("DB_NAME", "app_master"),
}


ALTERS = [
    "ALTER TABLE board_posts ADD COLUMN is_popup BOOLEAN DEFAULT FALSE AFTER is_active",
]


CREATE_DISMISSALS = """
CREATE TABLE IF NOT EXISTS board_post_dismissals (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id VARCHAR(36) NOT NULL,
  post_id VARCHAR(36) NOT NULL,
  dismissed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY unique_user_post (user_id, post_id),
  INDEX idx_user_id (user_id),
  INDEX idx_post_id (post_id),
  INDEX idx_dismissed_at (dismissed_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
"""


def run():
    conn = None
    cursor = None
    try:
        conn = mysql.connector.connect(**DB_CONFIG)
        cursor = conn.cursor()
        print("DB Connected")

        for query in ALTERS:
            try:
                cursor.execute(query)
                conn.commit()
                print("OK:", query)
            except Error as e:
                if e.errno == 1060:  # Duplicate column
                    print("SKIP (already exists):", query)
                else:
                    raise

        cursor.execute(CREATE_DISMISSALS)
        conn.commit()
        print("OK: create board_post_dismissals")

        print("\n=== board notice popup migration completed ===")
    finally:
        if cursor is not None:
            cursor.close()
        if conn is not None and conn.is_connected():
            conn.close()
            print("DB connection closed")


if __name__ == "__main__":
    run()

