USE whp;

-- Per-customer Sitesmith entitlement (Bichon-style)
ALTER TABLE client_allowances
  ADD COLUMN IF NOT EXISTS sitesmith_enabled TINYINT(1) NOT NULL DEFAULT 0
    COMMENT 'When 1, user can call Sitesmith subject to monthly cap',
  ADD COLUMN IF NOT EXISTS sitesmith_monthly_cap INT DEFAULT NULL
    COMMENT 'NULL = use sitesmith.default_monthly_cap from settings.json',
  ADD COLUMN IF NOT EXISTS sitesmith_bonus_credits INT NOT NULL DEFAULT 0
    COMMENT 'Support-granted one-time generations; consumed before monthly cap';

-- Conversation persistence: one thread per site
CREATE TABLE IF NOT EXISTS sitesmith_threads (
  id INT AUTO_INCREMENT PRIMARY KEY,
  site_id INT NOT NULL UNIQUE,
  username VARCHAR(32) NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    ON UPDATE CURRENT_TIMESTAMP,
  INDEX idx_user (username)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS sitesmith_messages (
  id INT AUTO_INCREMENT PRIMARY KEY,
  thread_id INT NOT NULL,
  role ENUM('user','assistant') NOT NULL,
  content MEDIUMTEXT NOT NULL,
  response_type ENUM('replace','patch','ask','error') DEFAULT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_thread_created (thread_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS sitesmith_usage (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(32) NOT NULL,
  site_id INT NOT NULL,
  thread_id INT NOT NULL,
  message_id INT NOT NULL,
  model VARCHAR(128) NOT NULL,
  prompt_tokens INT NOT NULL DEFAULT 0,
  completion_tokens INT NOT NULL DEFAULT 0,
  cached_tokens INT NOT NULL DEFAULT 0,
  cost_usd DECIMAL(10,6) NOT NULL DEFAULT 0,
  consumed_from ENUM('bonus','monthly') NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_user_month (username, consumed_from, created_at),
  INDEX idx_site (site_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
