import os
import mysql.connector


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"),
}


CREATE_JOBS_TABLE = """
CREATE TABLE IF NOT EXISTS babynote_kidsnote_sweetbook_jobs (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  request_id VARCHAR(36) NOT NULL,
  payment_order_id VARCHAR(36) DEFAULT NULL,
  job_type VARCHAR(50) NOT NULL DEFAULT 'create_order',
  status ENUM('pending', 'processing', 'completed', 'failed') NOT NULL DEFAULT 'pending',
  attempt_count INT NOT NULL DEFAULT 0,
  max_attempts INT NOT NULL DEFAULT 5,
  available_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  locked_at DATETIME DEFAULT NULL,
  lock_token VARCHAR(36) DEFAULT NULL,
  last_error VARCHAR(500) DEFAULT NULL,
  payload LONGTEXT DEFAULT NULL,
  processed_at DATETIME DEFAULT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uniq_request_id (request_id),
  INDEX idx_status_available (status, available_at),
  INDEX idx_lock_token (lock_token),
  INDEX idx_payment_order_id (payment_order_id),
  INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
"""


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

        cursor.execute(CREATE_JOBS_TABLE)
        connection.commit()
        print("OK: create babynote_kidsnote_sweetbook_jobs")

        print("\n=== babynote kidsnote Production jobs migration completed ===")
    finally:
        if cursor is not None:
            cursor.close()
        if connection is not None and connection.is_connected():
            connection.close()
            print("DB connection closed")


if __name__ == "__main__":
    run()
