import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";
import { NextResponse, NextRequest } from "next/server";
import { Database } from "@/types/supabase";
import prisma from "@/lib/prisma";
import { ProjectResponse } from "@/types";

async function getSession(supabase: any) {
  const {
    data: { session },
  } = await supabase.auth.getSession();
  return session;
}

// function that takes in workspaceID and gets all profile ids associated with that workspace id in the profile_workspace junction table. then, get all the profile emails associated with those profile ids. return the emails as an array.
export async function GET(
  req: NextRequest,
  { params: { workspaceID } }: { params: { workspaceID: string } }
) {
  const supabase = createRouteHandlerClient<Database>({ cookies });
  const session = await getSession(supabase);

  if (!session) return NextResponse.redirect("/auth");

  try {
    const profile_workspaces = await prisma.profile_workspace.findMany({
      where: {
        workspace_id: BigInt(workspaceID),
      },
    });

    const profile_ids = profile_workspaces.map((profile_workspace) => {
      return profile_workspace.profile_id;
    });

    const profiles = await prisma.profile.findMany({
      where: {
        id: {
          in: profile_ids,
        },
      },
    });

    // get all emails and profile ids
    const emails = profiles.map((profile) => {
      return {
        email: profile.email,
        id: profile.id,
      };
    });

    return NextResponse.json({ emails }, { status: 200 });
  } catch (err) {
    console.error(err);
    return NextResponse.json({ error: err }, { status: 500 });
  }
}