import axios from "axios";
import db from "../../models/index.js";

const { AlertBank, Op, Sequelize, sequelize } = db;
import { getValidDeviceIds } from "./getValidDeviceIds.service.js";
import { secondaryDB } from "../../config/db.js";

// ========== CONSTANTS ==========

const TEN_MIN_MS = 10 * 60 * 1000;
let isRunning = false;

// ========== HELPERS ==========
function getDateOnly(date: string | number | Date): string | null {
  if (!date) return null;
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

function formatToIST(dateString: any): string {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

function parseAsLocalDate(dateString: string): Date {
  const [datePart, timePart] = dateString.split(" ");
  const [year, month, day] = datePart.split("-");
  const [hours, minutes, seconds] = timePart.split(":");
  return new Date(+year, +month - 1, +day, +hours, +minutes, +seconds);
}

function getISTDate(): Date {
  const now = new Date();
  return new Date(now.toLocaleString("en-US", { timeZone: "Asia/Kolkata" }));
}

const parseDurationToMinutes = (modeTime: string): number => {
  if (!modeTime || modeTime === "N/A") return 0;
  const timeStr = modeTime.toLowerCase();
  let totalMinutes = 0;
  const daysMatch = timeStr.match(/(\d+)\s*days?/);
  if (daysMatch) totalMinutes += parseInt(daysMatch[1]) * 24 * 60;
  const hoursMatch = timeStr.match(/(\d+)\s*hrs?/);
  if (hoursMatch) totalMinutes += parseInt(hoursMatch[1]) * 60;
  const minutesMatch = timeStr.match(/(\d+)\s*min/);
  if (minutesMatch) totalMinutes += parseInt(minutesMatch[1]);
  return totalMinutes;
};

const getPositivePoi = (poi: unknown): string | null => {
  if (typeof poi !== "string") return null;

  const distanceMatch = poi.match(/(\d+(?:\.\d+)?)\s*KM\b/i);
  if (!distanceMatch || Number(distanceMatch[1]) <= 0) return null;

  return poi;
};

function suppressAlertsWithin10Min(
  alerts: {
    user_id: any;
    group_id: any;
    alert_type: any;
    vehicleno: any;
    gps_time: Date;
    created_at: Date;
    sys_service_id: any;
    msg: string;
  }[],
) {
  const sortedAlerts = [...alerts].sort(
    (a, b) => new Date(a.gps_time).getTime() - new Date(b.gps_time).getTime(),
  );
  const suppressedAlerts: typeof alerts = [];
  const suppressionMap = new Map<string, number>();

  for (const alert of sortedAlerts) {
    const key = `${alert.vehicleno}-${alert.alert_type}`;
    const alertTime = new Date(alert.gps_time).getTime();
    const lastAlertTime = suppressionMap.get(key);

    if (!lastAlertTime) {
      suppressedAlerts.push(alert);
      suppressionMap.set(key, alertTime);
      continue;
    }

    if (alertTime - lastAlertTime >= TEN_MIN_MS) {
      suppressedAlerts.push(alert);
      suppressionMap.set(key, alertTime);
    }
  }
  return suppressedAlerts;
}

async function upsertAlert(
  alert: any,
  targetDate: string,
): Promise<"created" | "updated"> {
  const start = new Date(targetDate + "T00:00:00+05:30");
  const end = new Date(targetDate + "T23:59:59+05:30");

  const whereClause: any = {
    user_id: alert.user_id,
    vehicleno: alert.vehicleno,
    alert_type: alert.alert_type,
    sys_service_id: alert.sys_service_id,
    created_at: {
      [Op.between]: [start, end],
    },
  };

  // For Vehicle Health Alert, also match SPN code via msg
  if (alert.alert_type === "Vehicle Health Alert" && alert.spnCode) {
    whereClause.msg = { [Op.like]: `%SPN%${alert.spnCode}%` };
  }

  const result = await secondaryDB.transaction(async (t) => {
    const existing = await AlertBank.findOne({
      where: whereClause,
      order: [["gps_time", "DESC"]],
      transaction: t,
      lock: t.LOCK.UPDATE,
    });

    if (existing) {
      await existing.update(
        {
          msg: alert.msg,
          issue: alert.issue,
          gps_time: alert.gps_time,
          updated_at: getISTDate(),
        },
        { transaction: t },
      );
      return "updated";
    }

    await AlertBank.create(alert, { transaction: t });
    return "created";
  });
  return result;
}

// ========== DEFAULTS ==========

const DEFAULT_ACCOUNTS = [
  { userid: 81707, token: 53823 },
  { userid: 4343, token: 4378 },
  { userid: 87115, token: 59343 },
  { userid: 833868, token: 60632 },
  { userid: 3212, token: 3236 },
  // { userid: 833940, token: 60704 },
  { userid: 834092, token: 60855 },
];

const IDLE_ONLY_ACCOUNTS = new Set(["834092-60855"]);

const ALL_ALERT_TYPES = [
  "Idle",
  "Smoke",
  "Fasten Seat Belt",
  "Tired",
  "Phone Call",
  "Lesser KM/DAY",
  "Enroute Halt Alert",
  "Enroute Halt",
  "Geofence Halt Alert",
  "Vehicle Health Alert",
  "Unhealthy Elock Alert",
  "Mainpower Disconnected",
  "Coverning Camera",
  "Main Power Disconnected",
];

// Alert types that use "upsert by day" logic (stationary-vehicle / daily alerts)
const UPSERT_BY_DAY_TYPES = new Set([
  "Idle",
  "Enroute Halt Alert",
  "Enroute Halt",
  "Geofence Halt Alert",
  "Unhealthy Elock Alert",
  "Mainpower Disconnected",
  "Lesser KM/DAY",
  "Vehicle Health Alert",
  "Fasten Seat Belt",
  "Phone Call",
  "Smoke",
  "Coverning Camera",
  "Main Power Disconnected",
]);

// ========== CONTROLLER ==========

const storeAlerts = async (req: any, res: any) => {
  const { startTime, endTime, source = "both" } = req.query;
  const { accounts = DEFAULT_ACCOUNTS } = req.body || {};

  if (!Array.isArray(accounts) || accounts.length === 0) {
    return res
      .status(400)
      .json({ msg: "accounts array with userid and token is required" });
  }

  if (!startTime || !endTime) {
    return res.status(400).json({
      msg: "startTime and endTime are required",
      error: "Missing required parameters",
    });
  }

  if (isRunning) {
    // console.log("⚠️ Job already running, skipping...");
    return res.status(429).json({
      msg: "Job already running, try again shortly",
    });
  }

  isRunning = true;

  try {
    // ---- FIX #3: key = `${user_id}-${alert_type}` ----
    const lastEntries = await AlertBank.findAll({
      attributes: [
        "user_id",
        "alert_type",
        [Sequelize.fn("MAX", Sequelize.col("gps_time")), "last_gps_time"],
      ],
      where: { alert_type: ALL_ALERT_TYPES },
      group: ["user_id", "alert_type"],
      raw: true,
    });

    const lastGpsTimeByType: Record<string, Date> = {};
    lastEntries.forEach((entry: any) => {
      const key = `${entry.user_id}-${entry.alert_type}`;
      lastGpsTimeByType[key] = new Date(entry.last_gps_time);
    });

    let allMappedData: any[] = [];
    const errors: string[] = [];

    for (const account of accounts) {
      const { userid, token } = account;

      if (!userid || !token) {
        // console.warn("Skipping invalid account:", account);
        continue;
      }

      const bjsOnly =
        (userid === 833868 && token === 60632) ||
        (userid === 3212 && token === 3236);

      // ================ ENROUTE HALT ALERTS =================
      if (
        !bjsOnly &&
        !IDLE_ONLY_ACCOUNTS.has(`${userid}-${token}`) &&
        (source === "halt" || source === "both")
      ) {
        try {
          const unrouteURL = `https://gtrac.in:8081/trackingDashboard/getListVehiclesmobFinal?token=${token}&userid=${userid}&puserid=1&mode=`;
          const resp2 = await axios.get(unrouteURL, { timeout: 60000 });
          const list = resp2.data?.list || [];

          const filtered = list.filter((item: any) => {
            const poi = item?.gpsDtl?.latLngDtl?.poi;
            const elockPOI = item?.gpsDtl?.ELOCKInfo?.poi;
            const modeTime = item?.gpsDtl?.modeTime;
            const isNonActive = item?.gpsDtl?.inactiveStatus === 1;
            if (isNonActive) return false;
            if (poi !== "No Nearest POI") return false;
            if (elockPOI && elockPOI !== "No Nearest POI") return false;
            if (!modeTime) return false;
            const totalMin = parseDurationToMinutes(modeTime);
            return totalMin != null && totalMin > 30;
          });

          const haltMapped = filtered.map((v: any) => {
            const gpsTimeRaw = v.gpsDtl?.latLngDtl?.gpstime;
            const formattedGpsTime = gpsTimeRaw
              ? formatToIST(gpsTimeRaw)
              : null;
            return {
              user_id: userid,
              group_id: token,
              alert_type: "Enroute Halt Alert",
              vehicleno: v.vehReg,
              gps_time: formattedGpsTime
                ? parseAsLocalDate(formattedGpsTime)
                : null,
              created_at: getISTDate(),
              sys_service_id: v.vId,
              issue: v.gpsDtl?.modeTime,
              msg: `ALERT: Enroute Halt Alert detected for vehicle ${v.vehReg} on ${formattedGpsTime} at ${v.gpsDtl?.latLngDtl?.addr}`,
            };
          });

          allMappedData.push(...haltMapped);
        } catch (error: any) {
          // console.error("HALT Error:", error.message);
          errors.push(`Enroute Halt: ${error.message}`);
        }
      }

      // ==================== IDLE ALERTS ====================
      if (
        IDLE_ONLY_ACCOUNTS.has(`${userid}-${token}`) &&
        (source === "idle" || source === "both")
      ) {
        try {
          const idleURL = `https://gtrac.in:8081/trackingDashboard/getListVehiclesmobFinal?token=${token}&userid=${userid}&puserid=833940&mode=`;
          const resp2 = await axios.get(idleURL, { timeout: 60000 });
          const list = resp2.data?.list || [];

          const filtered = list.filter((item: any) => {
            const poi = item?.gpsDtl?.latLngDtl?.poi;
            const mode = String(item?.gpsDtl?.mode || "").toUpperCase();
            const modeTime = item?.gpsDtl?.modeTime;
            const isNonActive = item?.gpsDtl?.inactiveStatus === 1;

            if (isNonActive || !modeTime) return false;
            if (mode !== "IDLE" && mode !== "STOPPED") return false;
            if (!getPositivePoi(poi)) return false;
            return parseDurationToMinutes(modeTime) > 15;
          });

          const idleMapped = filtered.map((v: any) => {
            const gpsTimeRaw = v.gpsDtl?.latLngDtl?.gpstime;
            const formattedGpsTime = gpsTimeRaw
              ? formatToIST(gpsTimeRaw)
              : null;
            return {
              user_id: userid,
              group_id: token,
              alert_type: "Idle",
              vehicleno: v.vehReg,
              gps_time: formattedGpsTime
                ? parseAsLocalDate(formattedGpsTime)
                : null,
              created_at: getISTDate(),
              sys_service_id: v.vId,
              issue: v.gpsDtl?.modeTime,
              msg: `ALERT: Idle detected for vehicle ${v.vehReg} on ${formattedGpsTime} at ${v.gpsDtl?.latLngDtl?.poi} (${v.gpsDtl?.latLngDtl?.addr})`,
            };
          });

          allMappedData.push(...idleMapped);
        } catch (error: any) {
          errors.push(`Idle: ${error.message}`);
        }
      }

      // ================ UNHEALTHY ELOCK ALERTS =================
      if (!bjsOnly && (source === "unhealthy" || source === "both")) {
        try {
          const unrouteURL = `https://gtrac.in:8081/trackingDashboard/getListVehiclesmobFinal?token=${token}&userid=${userid}&puserid=1&mode=`;
          const resp2 = await axios.get(unrouteURL, { timeout: 60000 });
          const list = resp2.data?.list || [];

          const filtered = list.filter((item: any) => {
            const isTrue = item.ELOCKInfo?.Unhealthy?.data;
            return (
              isTrue &&
              Array.isArray(item.ELOCKInfo.Unhealthy.data) &&
              item.ELOCKInfo.Unhealthy.data[0] == 1
            );
          });

          const unhealthyMapped = filtered.map((v: any) => {
            const gpsTimeRaw = v.gpsDtl?.latLngDtl?.gpstime;
            const formattedGpsTime = gpsTimeRaw
              ? formatToIST(gpsTimeRaw)
              : null;
            return {
              user_id: userid,
              group_id: token,
              alert_type: "Unhealthy Elock Alert",
              vehicleno: v.vehReg,
              gps_time: formattedGpsTime
                ? parseAsLocalDate(formattedGpsTime)
                : null,
              created_at: getISTDate(),
              sys_service_id: v.vId,
              issue: v.gpsDtl?.modeTime,
              msg: `ALERT: Unhealthy Elock Alert detected for vehicle ${v.vehReg} on ${formattedGpsTime} at ${v.gpsDtl?.latLngDtl?.addr}`,
            };
          });

          allMappedData.push(...unhealthyMapped);
        } catch (error: any) {
          // console.error("Unhealthy Elock Error:", error.message);
          errors.push(`Unhealthy Elock: ${error.message}`);
        }
      }

      // ================ MAINPOWER DISCONNECTED ALERTS =================
      if (!bjsOnly && (source === "mainpower" || source === "both")) {
        try {
          const unrouteURL = `https://gtrac.in:8081/trackingDashboard/getListVehiclesmobFinal?token=59343&userid=87115&puserid=1&mode=`;
          const resp2 = await axios.get(unrouteURL, { timeout: 60000 });
          const list = resp2.data?.list || [];

          const filtered = list.filter(
            (item: any) => item.gpsDtl.ismainpoerconnected == "0",
          );

          const mainpowerMapped = filtered.map((v: any) => {
            const gpsTimeRaw = v.gpsDtl?.latLngDtl?.gpstime;
            const formattedGpsTime = gpsTimeRaw
              ? formatToIST(gpsTimeRaw)
              : null;
            return {
              user_id: 87115,
              group_id: 59343,
              alert_type: "Mainpower Disconnected",
              vehicleno: v.vehReg,
              gps_time: formattedGpsTime
                ? parseAsLocalDate(formattedGpsTime)
                : null,
              created_at: getISTDate(),
              sys_service_id: v.vId,
              issue: v.gpsDtl?.modeTime,
              msg: `ALERT: Mainpower Disconnected Alert detected for vehicle ${v.vehReg} on ${formattedGpsTime} at ${v.gpsDtl?.latLngDtl?.addr}`,
            };
          });

          allMappedData.push(...mainpowerMapped);
        } catch (error: any) {
          // console.error("Mainpower Disconnected Error:", error.message);
          errors.push(`Mainpower Disconnected: ${error.message}`);
        }
      }

      // ================ ENROUTE HALT ALERTS FOR GDL =================
      if (!bjsOnly && (source === "gdl" || source === "both")) {
        try {
          const unrouteURL =
            "https://gtrac.in:8081/trackingDashboard/getListVehiclesmobFinal?token=6364&userid=6461&puserid=1&mode=";
          const resp2 = await axios.get(unrouteURL, { timeout: 60000 });
          const list = resp2.data?.list || [];

          const filtered = list.filter((item: any) => {
            const poi = item?.gpsDtl?.latLngDtl?.poi;
            const addr = item?.gpsDtl?.latLngDtl?.addr;
            const modeTime = item?.gpsDtl?.modeTime;
            const mode = item?.gpsDtl?.mode;
            const isNonActive = item?.gpsDtl?.inactiveStatus === 1;
            if (isNonActive || !modeTime || !mode) return false;
            if (poi !== "Inside Geofence") return false;
            if (mode !== "STOPPED") return false;
            if (addr && addr.includes("BMCT PORT GATE")) return false;
            const totalMin = parseDurationToMinutes(modeTime);
            return totalMin > 15;
          });

          const haltMapped = filtered.map((v: any) => {
            const gpsTimeRaw = v.gpsDtl?.latLngDtl?.gpstime;
            const formattedGpsTime = gpsTimeRaw
              ? formatToIST(gpsTimeRaw)
              : null;
            return {
              user_id: 6461,
              group_id: 6364,
              alert_type: "Enroute Halt",
              vehicleno: v.vehReg,
              gps_time: formattedGpsTime
                ? parseAsLocalDate(formattedGpsTime)
                : null,
              created_at: getISTDate(),
              sys_service_id: v.vId,
              issue: v.gpsDtl?.modeTime,
              msg: `ALERT: Enroute Halt Alert detected for vehicle ${v.vehReg} on ${formattedGpsTime} at ${v.gpsDtl?.latLngDtl?.addr}`,
            };
          });

          allMappedData.push(...haltMapped);
        } catch (error: any) {
          // console.error("GDL HALT Error:", error.message);
          errors.push(`Enroute Halt GDL: ${error.message}`);
        }
      }

      // ================ MAINPOWER DISCONNECTED ALERTS =================
      if (!bjsOnly && (source === "mainpowerabc" || source === "both")) {
        try {
          const unrouteURL =
            "https://gtrac.in:8081/trackingDashboard/getListVehiclesmobFinal?token=60519&userid=833755&puserid=1&mode=";
          const resp2 = await axios.get(unrouteURL, { timeout: 60000 });
          const list = resp2.data?.list || [];

          const filtered = list.filter((item: any) => {
            const mainPowerDisconnected =
              item?.gpsDtl?.ismainpoerconnected == "0";
            if (mainPowerDisconnected) return true;
            return false;
          });

          const haltMapped = filtered.map((v: any) => {
            const gpsTimeRaw = v.gpsDtl?.latLngDtl?.gpstime;
            const formattedGpsTime = gpsTimeRaw
              ? formatToIST(gpsTimeRaw)
              : null;
            return {
              user_id: 833755,
              group_id: 60519,
              alert_type: "Main Power Disconnected",
              vehicleno: v.vehReg,
              gps_time: formattedGpsTime
                ? parseAsLocalDate(formattedGpsTime)
                : null,
              created_at: getISTDate(),
              sys_service_id: v.vId,
              issue: v.gpsDtl?.modeTime,
              msg: `ALERT: Main Power Disconnected Alert detected for vehicle ${v.vehReg} on ${formattedGpsTime}`,
            };
          });

          allMappedData.push(...haltMapped);
        } catch (error: any) {
          // console.error("GDL HALT Error:", error.message);
          errors.push(`Main Power Disconnected GDL: ${error.message}`);
        }
      }

      // ================ GEOFENCE HALT ALERTS =================
      const isIdleOnlyAccount = IDLE_ONLY_ACCOUNTS.has(`${userid}-${token}`);
      if (
        !bjsOnly &&
        !isIdleOnlyAccount &&
        (source === "GEOFENCE" || source === "both")
      ) {
        try {
          const unrouteURL = `https://gtrac.in:8081/trackingDashboard/getListVehiclesmobFinal?token=${token}&userid=${userid}&puserid=1&mode=`;
          const resp2 = await axios.get(unrouteURL, { timeout: 60000 });
          const list = resp2.data?.list || [];

          const filtered = list.filter((item: any) => {
            const mode = item?.gpsDtl?.mode;
            const isNonActive = item?.gpsDtl?.inactiveStatus === 1;
            const modeTime = item?.gpsDtl?.modeTime;
            if (isNonActive || !mode || !modeTime) return false;
            if (mode !== "STOPPED") return false;
            const match = modeTime.match(/(\d+)\s*hrs:(\d+)\s*min/);
            if (!match) return false;
            const totalMin = +match[1] * 60 + +match[2];
            return totalMin > 2880;
          });

          const haltMapped = filtered.map((v: any) => {
            const gpsTimeRaw = v.gpsDtl?.latLngDtl?.gpstime;
            const formattedGpsTime = gpsTimeRaw
              ? formatToIST(gpsTimeRaw)
              : null;
            return {
              user_id: userid,
              group_id: token,
              alert_type: "Geofence Halt Alert",
              vehicleno: v.vehReg,
              gps_time: formattedGpsTime
                ? parseAsLocalDate(formattedGpsTime)
                : null,
              created_at: getISTDate(),
              sys_service_id: v.vId,
              issue: v.gpsDtl?.modeTime,
              msg: `ALERT: Geofence Halt Alert detected for vehicle ${v.vehReg} on ${formattedGpsTime} at ${v.gpsDtl?.latLngDtl?.addr}`,
            };
          });

          allMappedData.push(...haltMapped);
        } catch (error: any) {
          // console.error("GEOFENCE HALT Error:", error.message);
          errors.push(`Geofence Halt: ${error.message}`);
        }
      }

      // ================ LESSER KM/DAY ALERTS =================
      if (!bjsOnly && (source === "LESSER" || source === "both")) {
        function getYesterday(dateStr: any) {
          const d = parseAsLocalDate(dateStr);
          d.setDate(d.getDate() - 1);
          return formatToIST(d);
        }

        const yStart = getYesterday(startTime);
        const yEnd = getYesterday(endTime);
        const safeStart = yStart.replace(/ /g, "%20");
        const safeEnd = yEnd.replace(/ /g, "%20");

        try {
          const healtingAPI = `https://gtrac.in:8081/trackingDashboard/getHaltingHoursInPoi/?token=${token}`;
          const consolidateAPI = `https://gtrac.in:8081/trackingDashboard/consolidateKM/?token=${token}&startdate=${safeStart}&enddate=${safeEnd}`;

          const [resp1, resp2] = await Promise.all([
            axios.get(healtingAPI, { timeout: 60000 }),
            axios.get(consolidateAPI, { timeout: 60000 }),
          ]);

          let haltingList = resp1?.data?.list || [];
          const kmList = resp2?.data?.list || [];

          if (!Array.isArray(haltingList)) {
            haltingList = haltingList?.vehicleNum ? [haltingList] : [];
          }

          const result = haltingList
            .filter((h: any) => +h.total_halting_timeMin < 1080)
            .map((h: any) => {
              const haltingMin = +h.total_halting_timeMin;
              const workingMin = 1080 - haltingMin;
              const workingHours = workingMin / 60;
              const expectedKM = workingHours * 30;
              const kmData = kmList.find((k: any) => k.veh_id == h.vehicleNum);
              const actualKM = parseFloat(kmData?.kmshow || 0);
              return {
                ...h,
                vehicleno: kmData?.vehicleNum,
                sys_service_id: kmData?.veh_id,
                actualKM,
                expectedKM,
              };
            })
            .filter((v: any) => v.actualKM >= 100 && v.actualKM < v.expectedKM);

          const stableGpsTime = parseAsLocalDate(yStart);

          const haltMapped = result.map((v: any) => ({
            user_id: userid,
            group_id: token,
            alert_type: "Lesser KM/DAY",
            vehicleno: v.vehicleno,
            gps_time: stableGpsTime,
            created_at: getISTDate(),
            sys_service_id: v.sys_service_id,
            issue: v.actualKM,
            msg: `ALERT: Lesser KM/DAY detected for vehicle ${v.vehicleno}. Expected KM: ${v.expectedKM.toFixed(2)}`,
          }));

          allMappedData.push(...haltMapped);
        } catch (error: any) {
          // console.error("Lesser KM/DAY Error:", error.message);
          errors.push(`Lesser KM/DAY: ${error.message}`);
        }
      }

      // ==================== BJS ALERTS ====================
      if (source === "bjs" || source === "both") {
        try {
          const validDeviceIds = await getValidDeviceIds({
            BSJ: true,
            userid,
            token,
          });

          if (validDeviceIds.length > 0) {
            const BJSAPI =
              "https://y.gpstracktech.com/api/alarm/recentlyAdasList";
            const alertRes = await axios.post(
              BJSAPI,
              {
                startTime,
                endTime,
                ids: [201, 38, 202, 213, 200, 209],
                pageNumber: 1,
                pageSize: 300,
                queryParams: validDeviceIds.map((v: any) => String(v.deviceId)),
                queryType: 1,
              },
              {
                headers: {
                  "Content-Type": "application/json",
                  key: "ba3c5a15-cd8a-4706-b9d7-b34a64244541",
                  "Accept-Language": "en",
                  version: "1.0",
                },
                timeout: 60000,
              },
            );

            const records = alertRes.data.data || [];
            // console.log(`BJS API returned ${records.length} alerts`);

            if (Array.isArray(records)) {
              const newRecords = records.filter((item: any) => {
                const alertType = item.alarmName || "0";
                // FIX #3: use user-scoped key
                const lastTime = lastGpsTimeByType[`${userid}-${alertType}`];
                const mediaType = item.aviPath;
                const filePath = item.imagePath;
                if (!mediaType || !filePath) return false;
                return !lastTime || new Date(item.alarmTime) > lastTime;
              });

              // console.log(`BJS new alerts to process: ${newRecords.length}`);

              const bjsMappedData = newRecords.map((item: any) => {
                const formattedGpsTime = formatToIST(item.alarmTime);
                return {
                  user_id: userid,
                  group_id: token,
                  alert_type: item.alarmName || "0",
                  vehicleno: item.deviceName || "0",
                  gps_time: parseAsLocalDate(formattedGpsTime),
                  created_at: getISTDate(),
                  sys_service_id:
                    validDeviceIds.find((d: any) => d.deviceId == item.deviceId)
                      ?.vId || 0,
                  msg: `ALERT: ${item.alarmName} detected for vehicle ${item.deviceName} at ${formattedGpsTime}`,
                };
              });

              const suppressedBjsMappedData =
                suppressAlertsWithin10Min(bjsMappedData);
              allMappedData.push(...suppressedBjsMappedData);
            }
          }
        } catch (error: any) {
          // console.error("BJS Error:", error.message);
          errors.push(`BJS: ${error.message}`);
        }
      }

      // ==================== BJS ALERTS ====================
      // if (source === "bjs" || source === "both") {
      //   try {
      //     const validDeviceIds = await getValidDeviceIds({
      //       BSJ: true,
      //       userid,
      //       token,
      //     });

      //     if (validDeviceIds.length > 0) {
      //       const BJSAPI =
      //         "https://y.gpstracktech.com/api/alarm/recentlyAdasList";
      //       const alertRes = await axios.post(
      //         BJSAPI,
      //         {
      //           startTime,
      //           endTime,
      //           ids: [201, 38, 202, 213, 200, 209],
      //           pageNumber: 1,
      //           pageSize: 300,
      //           queryParams: validDeviceIds.map((v: any) => String(v.deviceId)),
      //           queryType: 1,
      //         },
      //         {
      //           headers: {
      //             "Content-Type": "application/json",
      //             key: "ba3c5a15-cd8a-4706-b9d7-b34a64244541",
      //             "Accept-Language": "en",
      //             version: "1.0",
      //           },
      //           timeout: 60000,
      //         },
      //       );

      //       const records = alertRes.data.data || [];
      //       // console.log(`BJS API returned ${records.length} alerts`);

      //       if (Array.isArray(records)) {
      //         const newRecords = records.filter((item: any) => {
      //           const alertType = item.alarmName || "0";
      //           // FIX #3: use user-scoped key
      //           const lastTime = lastGpsTimeByType[`${userid}-${alertType}`];
      //           const mediaType = item.aviPath;
      //           const filePath = item.imagePath;
      //           if (!mediaType || !filePath) return false;
      //           return !lastTime || new Date(item.alarmTime) > lastTime;
      //         });

      //         // console.log(`BJS new alerts to process: ${newRecords.length}`);

      //         const bjsMappedData = newRecords.map((item: any) => {
      //           const formattedGpsTime = formatToIST(item.alarmTime);
      //           return {
      //             user_id: userid,
      //             group_id: token,
      //             alert_type: item.alarmName || "0",
      //             vehicleno: item.deviceName || "0",
      //             gps_time: parseAsLocalDate(formattedGpsTime),
      //             created_at: getISTDate(),
      //             sys_service_id:
      //               validDeviceIds.find((d: any) => d.deviceId == item.deviceId)
      //                 ?.vId || 0,
      //             msg: `ALERT: ${item.alarmName} detected for vehicle ${item.deviceName} at ${formattedGpsTime}`,
      //           };
      //         });

      //         const suppressedBjsMappedData =
      //           suppressAlertsWithin10Min(bjsMappedData);
      //         allMappedData.push(...suppressedBjsMappedData);
      //       }
      //     }
      //   } catch (error: any) {
      //     // console.error("BJS Error:", error.message);
      //     errors.push(`BJS: ${error.message}`);
      //   }
      // }

      // ==================== METTAX ALERTS ====================
      // if (!bjsOnly && (source === "mettax" || source === "both")) {
      //   if (userid == 87115 && token == 59343) continue;

      //   try {
      //     const validDeviceIds = await getValidDeviceIds({
      //       BSJ: false,
      //       userid,
      //       token,
      //     });

      //     if (validDeviceIds && validDeviceIds.length > 0) {
      //       const deviceIdsCSV = validDeviceIds
      //         .map((v: any) => v.deviceId)
      //         .join(",");
      //       const generateTokenURL =
      //         "https://mettaxiot.com/gps/v2/openapi/system/createToken";
      //       const getAlertsURL =
      //         "https://mettahub.mettaxiot.com/gps/v2/openapi/alarm/file/page";

      //       const METTAX_CREDS: Record<
      //         number,
      //         { apiKey: string; apiSecret: string }
      //       > = {
      //         81707: {
      //           apiKey: "SmYJXVR8RP",
      //           apiSecret: "OutvO9f2SPFRaFMqED1V",
      //         },
      //         4343: { apiKey: "aJKEBllMc2", apiSecret: "Y98YD99bRDc1TX3HvjQi" },
      //       };

      //       const creds = METTAX_CREDS[userid];
      //       if (!creds) {
      //         errors.push(`No Mettax creds for user ${userid}`);
      //         continue;
      //       }

      //       const tokenRes = await axios.post(
      //         generateTokenURL,
      //         { apiKey: creds.apiKey, apiSecret: creds.apiSecret },
      //         { timeout: 10000 },
      //       );

      //       const tokenData = tokenRes?.data?.data;
      //       if (tokenData) {
      //         const alertRes = await axios.post(
      //           getAlertsURL,
      //           {
      //             startTime,
      //             endTime,
      //             deviceIds: deviceIdsCSV,
      //             alarmType: null,
      //             pageSize: 100,
      //             pageIndex: 1,
      //           },
      //           {
      //             headers: {
      //               Authorization: tokenData,
      //               "Content-Type": "application/json",
      //             },
      //             timeout: 60000,
      //           },
      //         );

      //         const records = alertRes.data?.data?.records || [];
      //         // console.log(`Mettax API returned ${records.length} alerts`);

      //         const newRecords = records.filter((item: any) => {
      //           const alertType = item.alarmType || "0";

      //           const lastTime = lastGpsTimeByType[`${userid}-${alertType}`];
      //           return !lastTime || new Date(item.alarmTime) > lastTime;
      //         });

      //         // console.log(`Mettax new alerts to process: ${newRecords.length}`);

      //         const mettaxMappedData = newRecords.map((item: any) => {
      //           const formattedGpsTime = formatToIST(item.alarmTime);
      //           return {
      //             user_id: userid,
      //             group_id: token,
      //             alert_type: item.alarmType || "0",
      //             vehicleno: item.deviceName || "0",
      //             gps_time: parseAsLocalDate(formattedGpsTime),
      //             created_at: getISTDate(),
      //             sys_service_id:
      //               validDeviceIds.find((d: any) => d.deviceId == item.deviceId)
      //                 ?.vId || 0,
      //             msg: `ALERT: ${item.alarmType} detected for vehicle ${item.deviceName} at ${formattedGpsTime}`,
      //           };
      //         });

      //         allMappedData.push(...mettaxMappedData);
      //       }
      //     }
      //   } catch (error: any) {
      //     // console.error("Mettax Error:", error.message);
      //     errors.push(`Mettax: ${error.message}`);
      //   }
      // }
    }

    // ==================== STORE ALL ALERTS ====================
    if (allMappedData.length === 0) {
      return res.json({
        msg:
          errors.length > 0
            ? "No new alerts to store (some errors occurred)"
            : "No new alerts to store",
        count: 0,
        errors: errors.length > 0 ? errors : undefined,
      });
    }

    const TEN_MIN = 10 * 60 * 1000;
    const uniqueAlerts = allMappedData.filter(
      (alert, index, self) =>
        index ===
        self.findIndex(
          (a) =>
            a.user_id === alert.user_id &&
            a.vehicleno === alert.vehicleno &&
            a.alert_type === alert.alert_type &&
            a.spnCode === alert.spnCode &&
            Math.abs(
              new Date(a.gps_time).getTime() -
                new Date(alert.gps_time).getTime(),
            ) < TEN_MIN,
        ),
    );

    // console.log(
    //   `\nChecking ${uniqueAlerts.length} unique alerts against database...`,
    // );

    let createdCount = 0;
    let updatedCount = 0;

    for (const alert of uniqueAlerts) {
      if (UPSERT_BY_DAY_TYPES.has(alert.alert_type)) {
        const targetDate = getDateOnly(alert.created_at);

        if (!targetDate) {
          await AlertBank.create(alert);
          createdCount++;
          // console.log(
          //   `  ✓ Created (no date): ${alert.alert_type} - ${alert.vehicleno}`,
          // );
          continue;
        }

        const result = await upsertAlert(alert, targetDate);
        if (result === "updated") {
          updatedCount++;
          // console.log(` ✓ Updated: ${alert.alert_type} - ${alert.vehicleno}`);
        } else {
          createdCount++;
          // console.log(`  ✓ Created: ${alert.alert_type} - ${alert.vehicleno}`);
        }
      } else {
        // For BJS/Mettax event-based alerts: always insert (they are point-in-time events)
        await AlertBank.create(alert);
        createdCount++;
        // console.log(
        //   `  ✓ Created New: ${alert.alert_type} - ${alert.vehicleno}`,
        // );
      }
    }

    // console.log(`\n=== SUMMARY ===`);
    // console.log(`Total fetched from APIs: ${allMappedData.length}`);
    // console.log(`After in-memory dedup: ${uniqueAlerts.length}`);
    // console.log(`New alerts created: ${createdCount}`);
    // console.log(`Existing alerts updated: ${updatedCount}`);

    return res.json({
      msg: "Alerts processed successfully",
      created: createdCount,
      updated: updatedCount,
      total: createdCount + updatedCount,
      source,
      totalFetched: allMappedData.length,
      // data: allMappedData,
      duplicatesRemoved: allMappedData.length - uniqueAlerts.length,
      errors: errors.length > 0 ? errors : undefined,
    });
  } catch (error: any) {
    // console.error("Error:", error);
    return res.status(500).json({
      msg: "Something went wrong",
      error: error.message,
      stack: process.env.NODE_ENV === "development" ? error.stack : undefined,
    });
  } finally {
    isRunning = false;
  }
};

export default storeAlerts;
