import { initDb } from "@/lib/db";

export interface SmtpSettings {
  host: string;
  port: number;
  user: string;
  password: string;
  from: string;
}

export interface PlatformSettings {
  signupsEnabled: boolean;
  maintenanceMode: boolean;
  smtp: SmtpSettings;
}

const DEFAULT_SMTP: SmtpSettings = {
  host: process.env.SMTP_HOST ?? "",
  port: Number(process.env.SMTP_PORT ?? 587),
  user: process.env.SMTP_USER ?? "",
  password: process.env.SMTP_PASSWORD ?? "",
  from: process.env.SMTP_FROM ?? "noreply@surveystronghold.com",
};

async function getSetting<T>(key: string, fallback: T): Promise<T> {
  const { SystemSetting } = initDb();
  const row = await SystemSetting.findOne({ where: { key } });
  if (!row || row.value === null || row.value === undefined) {
    return fallback;
  }
  return row.value as T;
}

async function upsertSetting(key: string, value: unknown) {
  const { SystemSetting } = initDb();
  const existing = await SystemSetting.findOne({ where: { key } });
  if (existing) {
    await existing.update({ value });
  } else {
    await SystemSetting.create({ key, value });
  }
}

/** Load platform settings (env defaults + DB overrides). */
export async function getPlatformSettings(): Promise<PlatformSettings> {
  const [signupsEnabled, maintenanceMode, smtp] = await Promise.all([
    getSetting("platform.signups_enabled", true),
    getSetting("platform.maintenance_mode", false),
    getSetting<SmtpSettings>("smtp", DEFAULT_SMTP),
  ]);

  return {
    signupsEnabled,
    maintenanceMode,
    smtp: { ...DEFAULT_SMTP, ...smtp },
  };
}

/** Persist platform toggles and SMTP config. */
export async function savePlatformSettings(input: PlatformSettings) {
  await Promise.all([
    upsertSetting("platform.signups_enabled", input.signupsEnabled),
    upsertSetting("platform.maintenance_mode", input.maintenanceMode),
    upsertSetting("smtp", input.smtp),
  ]);
}

/** Resolved SMTP for Nodemailer — DB overrides env. */
export async function getEffectiveSmtpSettings(): Promise<SmtpSettings> {
  const settings = await getPlatformSettings();
  return settings.smtp;
}
