import { Router } from "express";
import pool from "../config/db";
import { getApplicationTimezone, formatLocalIso } from "../config/time";

const router = Router();
const processStartedAt = new Date();
const databaseTimeoutMs = Math.max(250, Number(process.env.HEALTH_DB_TIMEOUT_MS) || 2500);

async function checkDatabase(): Promise<{ status: "up" | "down"; latency_ms: number; error?: string }> {
  const startedAt = Date.now();
  let timeout: NodeJS.Timeout | undefined;
  try {
    await Promise.race([
      pool.query("SELECT 1 AS ok"),
      new Promise<never>((_resolve, reject) => {
        timeout = setTimeout(() => reject(new Error("timeout")), databaseTimeoutMs);
      }),
    ]);
    return { status: "up", latency_ms: Date.now() - startedAt };
  } catch (error) {
    const message = error instanceof Error && error.message === "timeout" ? "timeout" : "unavailable";
    return { status: "down", latency_ms: Date.now() - startedAt, error: message };
  } finally {
    if (timeout) clearTimeout(timeout);
  }
}

router.use((_req, res, next) => {
  res.setHeader("Cache-Control", "no-store");
  next();
});

router.get("/live", (_req, res) => {
  const now = new Date();
  res.json({
    status: "ok",
    service: "lliria-properties-scraper",
    timestamp: now.toISOString(),
    uptime_seconds: Math.floor(process.uptime()),
  });
});

router.get("/", async (_req, res) => {
  const now = new Date();
  const database = await checkDatabase();
  const healthy = database.status === "up";
  const timezone = getApplicationTimezone();

  res.status(healthy ? 200 : 503).json({
    status: healthy ? "ok" : "degraded",
    service: "lliria-properties-scraper",
    timestamp: now.toISOString(),
    local_time: formatLocalIso(now, timezone),
    timezone,
    scheduler_enabled: process.env.SCHEDULER_ENABLED !== "false",
    uptime_seconds: Math.floor(process.uptime()),
    started_at: processStartedAt.toISOString(),
    checks: { database },
  });
});

export default router;
