import express, { Request, Response } from "express";
import https from "https";
import { URL } from "url";
import { getMasterBusinessPlanTemplate } from "../services/businessPlanTemplates";
import { getDownloadUrlAuto } from "../services/downloadUrl";

const router = express.Router();

/** Simple HTTPS HEAD helper. Returns HTTP status or 0 on error. */
function head(url: string): Promise<number> {
  return new Promise((resolve) => {
    try {
      const u = new URL(url);
      const req = https.request(
        {
          method: "HEAD",
          hostname: u.hostname,
          path: u.pathname + (u.search || ""),
          protocol: u.protocol,
        },
        (res) => {
          resolve(res.statusCode || 0);
        }
      );
      req.on("error", () => resolve(0));
      req.end();
    } catch {
      resolve(0);
    }
  });
}

router.get("/bp-templates", async (_req: Request, res: Response) => {
  const started = Date.now();
  try {
    const master = await getMasterBusinessPlanTemplate();
    if (!master) {
      return res.status(503).json({ ok: false, error: "No master template set" });
    }

    const slug = master.slug;
    const version = master.currentVersion || "unknown";
    const docxPath = master.storagePaths?.docx || "";
    const previewPath = master.storagePaths?.preview || "";
    const thumbPath = master.storagePaths?.thumb || "";

    // Build download URL (auto public/signed) and probe it
    const docxUrl = docxPath ? await getDownloadUrlAuto(docxPath) : "";
    const previewUrl = previewPath ? await getDownloadUrlAuto(previewPath) : "";
    const thumbUrl = thumbPath ? await getDownloadUrlAuto(thumbPath) : "";

    const [docxStatus, previewStatus, thumbStatus] = await Promise.all([
      docxUrl ? head(docxUrl) : Promise.resolve(0),
      previewUrl ? head(previewUrl) : Promise.resolve(0),
      thumbUrl ? head(thumbUrl) : Promise.resolve(0),
    ]);

    const mode = docxUrl.includes("X-Goog-Algorithm=") ? "signed" : "public";

    const payload = {
      ok: docxStatus === 200,
      time: new Date().toISOString(),
      ms: Date.now() - started,
      master: {
        slug,
        version,
        isMaster: !!master.isMaster,
      },
      storagePaths: { docxPath, previewPath, thumbPath },
      urls: { docxUrl, previewUrl, thumbUrl, mode },
      statuses: { docxStatus, previewStatus, thumbStatus },
    } as const;

    const statusCode = payload.ok ? 200 : 503;
    // Cache very briefly; this is a health endpoint
    res.set("Cache-Control", "no-cache, no-store, must-revalidate");
    return res.status(statusCode).json(payload);
  } catch (error: any) {
    return res.status(500).json({ ok: false, error: error?.message || "Health check failed" });
  }
});

export default router;
