import { NextRequest, NextResponse } from "next/server";
import { getClient } from "@/app/client";
import { cachedUntilOsloMidnight } from "@/lib/revalidation";
import {
  eventsOverviewQuery,
  getSingularEvents,
  getFutureOccurrences,
  EventOverviewItemFragment,
  EventCategory,
  EventOrganizer,
} from "@/lib/event";
import { VenueFragment } from "@/gql/graphql";

type CompactEvent = {
  id: string;
  slug: string;
  title: string;
  subtitle: string;
  nextOccurrence: {
    id: string;
    start: string;
    end?: string;
    venue: {
      id: string;
      slug: string;
      title: string;
      preposition: string;
      url: string;
    };
  };
};

type ResponseData = {
  events: CompactEvent[];
  total: number;
};

export async function GET(req: NextRequest) {
  const searchParams = req.nextUrl.searchParams;
  const view = searchParams.get("view");

  if (view !== "compact-app") {
    return NextResponse.json(
      { error: "must provide valid view parameter" },
      { status: 400 }
    );
  }

  const { data, error } = await getClient().query(
    eventsOverviewQuery,
    {},
    cachedUntilOsloMidnight()
  );
  if (error) {
    throw new Error(error.message);
  }
  if (
    !data?.index ||
    !data?.events?.futureEvents ||
    !data?.eventCategories ||
    !data?.eventOrganizers ||
    !data?.venues
  ) {
    throw new Error("Failed to fetch events");
  }

  const futureEvents = (data?.events?.futureEvents ?? []) as EventOverviewItemFragment[];
  const eventCategories = (data?.eventCategories ?? []) as EventCategory[];
  const eventOrganizers = (data?.eventOrganizers ?? []) as EventOrganizer[];
  const venues = (data?.venues ?? []) as VenueFragment[];

  const keepKeys = ["id", "slug", "title", "subtitle", "occurrence"];
  const compactEvents = futureEvents.map((event) => {
    const futureOccurrences = getFutureOccurrences(event);
    const nextOccurrence = futureOccurrences.length
      ? futureOccurrences[0]
      : null;

    return {
      id: event.id,
      slug: event.slug,
      title: event.title,
      subtitle: event.subtitle,
      nextOccurrence: nextOccurrence,
      url: `${process.env.URL}/arrangementer/${event.slug}`,
      futureOccurrencesCount: futureOccurrences.length,
    } as CompactEvent;
  });

  const responseData: ResponseData = {
    events: compactEvents,
    total: compactEvents.length,
  };

  return NextResponse.json(responseData, { status: 200 });
}
