CREATE TABLE IF NOT EXISTS users (
  id BIGINT PRIMARY KEY,
  username VARCHAR(64), first_name VARCHAR(128), last_name VARCHAR(128),
  language_code VARCHAR(16), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS sessions (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  user_id BIGINT NOT NULL,
  state ENUM('idea','analogs','trends','personal','strengths','subgate','feedback','upsell') NOT NULL DEFAULT 'idea',
  idea_text TEXT, pain_desc TEXT,
  analogs_input TEXT, trends_input TEXT, personal_input TEXT, strengths_input TEXT,
  unicorns_suggested TEXT, trends_suggested TEXT,
  feedback_strengths TEXT, feedback_weaknesses TEXT,
  verdict ENUM('yes','no') NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS messages (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  session_id BIGINT NOT NULL,
  role ENUM('system','user','assistant','tool') NOT NULL,
  msg_type ENUM('text','voice','system') NOT NULL DEFAULT 'text',
  content LONGTEXT, tg_message_id BIGINT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_messages_session_created (session_id, created_at)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS subscriptions (
  user_id BIGINT PRIMARY KEY,
  is_subscribed TINYINT(1) NOT NULL DEFAULT 0,
  last_checked_at TIMESTAMP NULL
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS images (
  id INT AUTO_INCREMENT PRIMARY KEY,
  filename VARCHAR(255) NOT NULL,
  tg_file_id VARCHAR(255) NULL,
  UNIQUE (filename)
) ENGINE=InnoDB;