import "dotenv/config";
import { loadConfigFile, getConfig } from "./configLoader.js";
import { initGameSchema, ensureSeedEpoch } from "./db/gameDb.js";
import { initUsersSchema } from "./db/usersDb.js";
import app from "./app.js";

const PORT = Number(process.env.PORT ?? 8080);

// ── Config-file poll ──────────────────────────────────────────────────────────
// Periodically re-reads game.settings.json and checks for a seed-epoch change.

function scheduleConfigPoll() {
  loadConfigFile();
  const ms = Math.max(5_000, getConfig().configReloadIntervalSeconds * 1_000);
  setTimeout(async () => {
    try {
      loadConfigFile();
      await ensureSeedEpoch();
    } catch (e) {
      console.error("[config poll]", e.message);
    }
    scheduleConfigPoll();
  }, ms);
}

// ── Boot ──────────────────────────────────────────────────────────────────────

async function main() {
  loadConfigFile();
  await initGameSchema();
  await initUsersSchema();
  await ensureSeedEpoch();

  app.listen(PORT, () => {
    const cfg = getConfig();
    console.log(
      `[server] Listening on :${PORT}  cooldown=${cfg.clickCooldownSeconds}s  wipe=${cfg.databaseWipeoutIntervalSeconds}s`
    );
  });

  scheduleConfigPoll();
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});