import { NextResponse } from "next/server";
import { getPool } from "@/lib/db";

const OLD_TABLE_CONFIG = [
  { table: "site_daily", outputKey: "site" },
  { table: "snapp_nextday_daily", outputKey: "nextDay" },
  { table: "snapp_daily", outputKey: "snapp" },
  { table: "digi_daily", outputKey: "digikala" },
  { table: "express_daily", outputKey: "express" },
];

const INCOMING_PARENT_MAP: Record<string, string> = {
  site: "site",
  digikala: "digi",
  snapp: "snapp",
  express: "express",
  nextDay: "nextDay",
};

interface OldRow {
  group_name: string;
  group_count: number;
  records: Array<{ row_index: number; G?: string }>;
}

export async function GET() {
  try {
    const pool = getPool();
    const merged: Record<string, any>[] = [];

    for (const { table, outputKey } of OLD_TABLE_CONFIG) {
      try {
        const [rows] = await pool.query(
          `SELECT group_name, group_count, records FROM \`${table}\``
        ) as unknown as [any[], any];
        const typedRows = rows as OldRow[];

        for (const row of typedRows) {
          const idxs = (row.records || [])
            .map((r) => {
              const n = parseInt(String(r.row_index), 10);
              return isNaN(n) ? r.row_index : n;
            })
            .filter((v) => v !== undefined && v !== null);

          idxs.sort((a: any, b: any) => {
            if (typeof a === "number" && typeof b === "number") return a - b;
            return String(a).localeCompare(String(b));
          });

          merged.push({
            [outputKey]: {
              group_name: row.group_name,
              group_count: row.group_count,
              rows_string: idxs.join(","),
            },
          });
        }
      } catch (err) {
        console.warn(`Error querying ${table}:`, err);
      }
    }

    const dailyG: Record<string, any[]> = {
      site: [], digi: [], snapp: [], express: [], nextDay: [],
      tapsiExpress: [], techno: [], digiMassnoat: [],
    };

    for (const item of merged) {
      const [incomingKey, group] = Object.entries(item)[0];
      const parent = INCOMING_PARENT_MAP[incomingKey];
      if (!parent) continue;

      const rows = (group.rows_string as string)
        .split(",")
        .map(Number)
        .filter((n) => !isNaN(n));

      dailyG[parent].push({
        group_name: group.group_name,
        records: rows.map((r: number) => ({ G: "", row_index: r })),
      });
    }

    const parents: (keyof typeof dailyG)[] = [
      "site", "digi", "snapp", "express", "nextDay",
      "tapsiExpress", "techno", "digiMassnoat",
    ];

    const output: any[] = [];
    for (const parent of parents) {
      const groups = dailyG[parent];
      for (const g of groups) {
        if (g?.group_name && Array.isArray(g.records)) {
          output.push({
            parent,
            group_name: g.group_name,
            objects_row_index: g.records.map((r: any) => r.row_index),
            count: g.records.length,
            type: "",
            key: "",
          });
        }
      }
    }

    return NextResponse.json([output]);
  } catch (err) {
    console.error("Error fetching daily-g2:", err);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
