import { Router, Request, Response } from "express";
import { storage } from "../storage";
import { io } from "../socket";
import { enqueueSeleniumJob } from "../queue/jobRunner";

const router = Router();

function log(tag: string, msg: string, ctx?: any) {
  console.log(`${new Date().toISOString()} [${tag}] ${msg}`, ctx ?? "");
}

/**
 * POST /cca-eligibility
 *
 * Enqueues a CCA (Commonwealth Care Alliance / ScionDental) eligibility check.
 * No OTP required — simple persistent session.
 *
 * Body:
 *   data     — patient + search fields (memberId, dateOfBirth, firstName, lastName)
 *   socketId — socket.io client id for real-time updates
 *
 * Response: { status: "queued", jobId: "…" }
 */
router.post(
  "/cca-eligibility",
  async (req: Request, res: Response): Promise<any> => {
    if (!req.body.data) {
      return res.status(400).json({ error: "Missing eligibility data for selenium" });
    }
    if (!req.user?.id) {
      return res.status(401).json({ error: "Unauthorized: user info missing" });
    }

    try {
      const rawData =
        typeof req.body.data === "string" ? JSON.parse(req.body.data) : req.body.data;

      // Fetch CCA credentials from DB
      const credentials = await storage.getInsuranceCredentialByUserAndSiteKey(
        req.user.id,
        "CCA"
      );
      if (!credentials) {
        return res.status(404).json({
          error: "No credentials found for CCA. Please add them on the Settings page.",
        });
      }

      const enrichedData = {
        ...rawData,
        cca_username: credentials.username,
        cca_password: credentials.password,
      };

      const socketId: string | undefined = req.body.socketId;

      const jobId = enqueueSeleniumJob({
        jobType: "cca-eligibility-check",
        userId: req.user.id,
        socketId,
        enrichedPayload: enrichedData,
        insuranceId: String(rawData.memberId ?? "").trim(),
        formFirstName: rawData.firstName,
        formLastName: rawData.lastName,
        formDob: rawData.dateOfBirth,
      });

      log("cca-route", "job enqueued", { jobId, insuranceId: rawData.memberId });

      return res.json({ status: "queued", jobId });
    } catch (err: any) {
      console.error("[cca-route] enqueue failed:", err);
      return res.status(500).json({
        error: err.message || "Failed to enqueue CCA selenium job",
      });
    }
  }
);

export default router;
