// app/api/data/route.ts
import { NextResponse } from "next/server";
import fs from "fs";
import path from "path";
import { HeaderResponse } from "@/lib/types/models";

export const revalidate = 7200;

export async function GET() {
  try {
    // Step 1: Fetch external API
    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/collections`,
      {
        cache: "no-store",
      }
    );
    const data: HeaderResponse = await response.json();
    // Step 2: Define file path inside /public
    const filePath = path.join(process.cwd(), "public", "menufile.json");

    // Step 3: Write JSON file (overwrites each request)
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2));

    // Step 4: Return response
    return NextResponse.json({
      success: true,
      message: "JSON file created successfully",
    });
  } catch (error) {
    return NextResponse.json(
      { success: false, error: "Failed to process request " + error },
      { status: 500 }
    );
  }
}
