import { backupConfig, startBackups } from "./ops/backups";
import { databasePath } from "./db/config";
import { db, sqlite } from "./db";
import { createApi } from "./api";
import { readAuthConfig } from "./auth/config";
import { readDiscordSharingConfig } from "./sharing/config";
import index from "./index.html";

const backups = process.env.NODE_ENV === "production" ? startBackups(sqlite, backupConfig(databasePath)) : undefined;
if (import.meta.hot) import.meta.hot.dispose(() => backups?.stop());

const app = createApi(db, readAuthConfig(), undefined, undefined, undefined, readDiscordSharingConfig(), { healthy: () => !backups?.state.enabled || (!backups.state.failed && backups.state.lastSuccess > 0) });

const server = Bun.serve({
  hostname: "127.0.0.1",
  port: Number(process.env.PORT ?? 3000),
  routes: {
    "/api": req => app.fetch(req),
    "/api/*": req => app.fetch(req),
    "/*": index,
  },
  development: process.env.NODE_ENV !== "production" && {
    hmr: true,
    console: true,
  },
});

console.log(`Server running at ${server.url}`);
