const { db } = require("./db");
const { envBoolean, envNumber, envString } = require("./config");

const ENV_DEFAULTS = {
  discord_client_id: "DISCORD_CLIENT_ID",
  discord_client_secret: "DISCORD_CLIENT_SECRET",
  discord_bot_token: "DISCORD_BOT_TOKEN",
  discord_guild_id: "DISCORD_GUILD_ID",
  discord_admin_role_id: "DISCORD_ADMIN_ROLE_ID",
  discord_mod_role_id: "DISCORD_MOD_ROLE_ID",
  discord_redirect_uri: "DISCORD_REDIRECT_URI",
  twitch_client_id: "TWITCH_CLIENT_ID",
  twitch_client_secret: "TWITCH_CLIENT_SECRET",
  twitch_redirect_uri: "TWITCH_REDIRECT_URI",
  twitch_bot_username: "TWITCH_BOT_USERNAME",
  twitch_bot_oauth: "TWITCH_BOT_OAUTH",
  twitch_channels: "TWITCH_CHANNELS",
  youtube_client_id: "YOUTUBE_CLIENT_ID",
  youtube_client_secret: "YOUTUBE_CLIENT_SECRET",
  youtube_redirect_uri: "YOUTUBE_REDIRECT_URI",
  youtube_bot_refresh_token: "YOUTUBE_BOT_REFRESH_TOKEN",
  youtube_bot_channel_id: "YOUTUBE_BOT_CHANNEL_ID"
};

function getSetting(key, fallback = null) {
  const row = db.prepare("SELECT value FROM settings WHERE key = ?").get(key);
  if (!row) {
    return getEnvDefault(key, fallback);
  }
  try {
    return JSON.parse(row.value);
  } catch {
    return row.value;
  }
}

function setSetting(key, value) {
  const now = Date.now();
  db.prepare(
    "INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?) " +
      "ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at"
  ).run(key, JSON.stringify(value), now);
}

function getAllSettings() {
  const rows = db.prepare("SELECT key, value FROM settings").all();
  const settings = {};
  for (const row of rows) {
    try {
      settings[row.key] = JSON.parse(row.value);
    } catch {
      settings[row.key] = row.value;
    }
  }
  return settings;
}

function ensureDefaults() {
  const defaults = {
    site_title: "Lumi Bot",
    command_prefix: envString("COMMAND_PREFIX", "!"),
    discord_client_id: envString("DISCORD_CLIENT_ID", ""),
    discord_client_secret: envString("DISCORD_CLIENT_SECRET", ""),
    discord_bot_token: envString("DISCORD_BOT_TOKEN", ""),
    discord_guild_id: envString("DISCORD_GUILD_ID", ""),
    discord_admin_role_id: envString("DISCORD_ADMIN_ROLE_ID", ""),
    discord_mod_role_id: envString("DISCORD_MOD_ROLE_ID", ""),
    discord_redirect_uri: envString("DISCORD_REDIRECT_URI", ""),
    auto_update_enabled: envBoolean("AUTO_UPDATE_ENABLED", false),
    auto_update_interval_minutes: envNumber("AUTO_UPDATE_INTERVAL_MINUTES", 60),
    production_diagnostics_enabled: false,
    log_retention_days: 30,
    log_retention_max_entries: 100000,
    git_remote: envString("GIT_REMOTE", "origin"),
    git_branch: envString("GIT_BRANCH", "main"),
    bot_avatar_url: null,
    platform_discord_enabled: envBoolean("PLATFORM_DISCORD_ENABLED", true),
    platform_kick_enabled: envBoolean("PLATFORM_KICK_ENABLED", false),
    platform_twitch_enabled: envBoolean("PLATFORM_TWITCH_ENABLED", true),
    platform_youtube_enabled: envBoolean("PLATFORM_YOUTUBE_ENABLED", false),
    twitch_client_id: envString("TWITCH_CLIENT_ID", ""),
    twitch_client_secret: envString("TWITCH_CLIENT_SECRET", ""),
    twitch_redirect_uri: envString("TWITCH_REDIRECT_URI", ""),
    twitch_bot_username: envString("TWITCH_BOT_USERNAME", ""),
    twitch_bot_oauth: envString("TWITCH_BOT_OAUTH", ""),
    twitch_channels: envString("TWITCH_CHANNELS", ""),
    youtube_client_id: envString("YOUTUBE_CLIENT_ID", ""),
    youtube_client_secret: envString("YOUTUBE_CLIENT_SECRET", ""),
    youtube_redirect_uri: envString("YOUTUBE_REDIRECT_URI", ""),
    youtube_bot_refresh_token: envString("YOUTUBE_BOT_REFRESH_TOKEN", ""),
    youtube_bot_channel_id: envString("YOUTUBE_BOT_CHANNEL_ID", ""),
    custom_placeholders: [],
    localhost_login_username: "admin",
    localhost_login_password: "admin",
    theme_light_bg_1: "#ffe5c4",
    theme_light_bg_2: "#f4efe8",
    theme_light_bg_3: "#e9f3f1",
    theme_light_text: "#121518",
    theme_light_text_muted: "#2c3137",
    theme_light_accent: "#0f6a78",
    theme_light_accent_alt: "#f4a340",
    theme_light_danger: "#d66d5c",
    theme_light_surface: "#ffffff",
    theme_light_surface_2: "#fbf9f6",
    theme_light_surface_3: "#f9f5ef",
    theme_light_border: "#e3ddd6",
    theme_dark_bg_1: "#1b1d1f",
    theme_dark_bg_2: "#16181b",
    theme_dark_bg_3: "#0f1113",
    theme_dark_text: "#f2f0ec",
    theme_dark_text_muted: "#c5bfb7",
    theme_dark_accent: "#4fb6c2",
    theme_dark_accent_alt: "#f1b765",
    theme_dark_danger: "#e08173",
    theme_dark_surface: "#232629",
    theme_dark_surface_2: "#2b2f33",
    theme_dark_surface_3: "#30353a",
    theme_dark_border: "#34393d",
    theme_role_public: "#ffffff",
    theme_role_mod: "#2cb678",
    theme_role_admin: "#e35678"
  };

  for (const [key, value] of Object.entries(defaults)) {
    if (getSetting(key) === null) {
      setSetting(key, value);
    }
  }
}

function getEnvDefault(key, fallback) {
  const envKey = ENV_DEFAULTS[key];
  if (!envKey) {
    return fallback;
  }
  return envString(envKey, fallback);
}

module.exports = {
  getSetting,
  setSetting,
  getAllSettings,
  ensureDefaults
};
