import { app } from "./app.js";
import { env } from "./config/env.js";
import { pool } from "./db/pool.js";
import { runMaintenanceCycle } from "./modules/maintenance/maintenance.service.js";

const server = app.listen(env.API_PORT, env.API_HOST, () => {
  console.log(`[api] Listening on ${env.API_BASE_URL} (bind ${env.API_HOST}:${env.API_PORT})`);
});

let maintenanceRunning = false;

async function executeMaintenance(reason: string): Promise<void> {
  if (maintenanceRunning) return;
  maintenanceRunning = true;
  try {
    const summary = await runMaintenanceCycle();
    console.log(`[maintenance] ${reason}:`, JSON.stringify(summary));
  } catch (err) {
    console.error(`[maintenance] ${reason} failed:`, err);
  } finally {
    maintenanceRunning = false;
  }
}

if (env.MAINTENANCE_JOB_ENABLED) {
  void executeMaintenance("startup");
  setInterval(() => {
    void executeMaintenance("scheduled");
  }, 24 * 60 * 60 * 1000);
}

async function shutdown(signal: string): Promise<void> {
  console.log(`[api] Received ${signal}. Shutting down...`);
  server.close(async () => {
    await pool.end();
    process.exit(0);
  });
}

process.on("SIGINT",  () => void shutdown("SIGINT"));
process.on("SIGTERM", () => void shutdown("SIGTERM"));
