// /pages/api/cpl/messages.ts
import { NextApiRequest, NextApiResponse } from "next";
import path from "path";
import { promises as fs } from "fs";

function parseDate(str: string): Date {
  return new Date(str.replace(" ", "T"));
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { from, to, MSS1 } = req.query;

  const filePath = path.join(
    process.cwd(),
    "apiMockData/meldungen/messages.json"
  );
  const fileContents = await fs.readFile(filePath, "utf-8");
  const data = JSON.parse(fileContents);

  let fromDate: Date | null = null;
  let toDate: Date | null = null;

  if (from && to) {
    fromDate = new Date(from.toString());
    toDate = new Date(to.toString());
    toDate.setHours(23, 59, 59, 999);
  } else if (MSS1) {
    const parts = MSS1.toString().split(";");
    if (parts.length >= 6) {
      const [fy, fm, fd, ty, tm, td] = parts;
      fromDate = new Date(`${fy}-${fm}-${fd}`);
      toDate = new Date(`${ty}-${tm}-${td}`);
      toDate.setHours(23, 59, 59, 999);
    }
  }

  if (fromDate && toDate) {
    const filtered = data.filter((msg: any) => {
      const messageDate = parseDate(msg.t);
      return messageDate >= fromDate! && messageDate <= toDate!;
    });

    console.log(
      "⏱ Zeitraum:",
      fromDate.toISOString(),
      "→",
      toDate.toISOString()
    );
    console.log("📦 Gefunden:", filtered.length);
    return res.status(200).json(filtered.slice(0, 500));
  }

  res.status(200).json(data.slice(0, 500));
}
