import { NextResponse } from "next/server";
import { typedQuery } from "@/backend/utils/typedQuery";

export const dynamic = "force-dynamic";
export const revalidate = 0;

type TermsRow = {
  categoryName: string;
  categoryOrder: number;
  descriptionPoint: string;
  pointOrder: number;
};

type TermsGroup = {
  category: string;
  points: string[];
};

export async function GET() {
  try {
    const [rows] = await typedQuery<TermsRow>(
      `
      SELECT
        category_name AS categoryName,
        category_order AS categoryOrder,
        description_point AS descriptionPoint,
        point_order AS pointOrder
      FROM scroll_popup_terms_conditions
      WHERE is_active = 1
      ORDER BY category_order ASC, point_order ASC, idscroll_popup_terms_condition ASC
      `
    );

    const groupedMap = new Map<string, TermsGroup>();

    for (const row of rows) {
      if (!groupedMap.has(row.categoryName)) {
        groupedMap.set(row.categoryName, { category: row.categoryName, points: [] });
      }
      groupedMap.get(row.categoryName)?.points.push(row.descriptionPoint);
    }

    return NextResponse.json({ terms: Array.from(groupedMap.values()) });
  } catch (error) {
    console.error("[ERROR] Failed to load scroll popup terms:", error);
    return NextResponse.json({ terms: [] }, { status: 200 });
  }
}
