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 email, checks if there is a user associated. if there is, get the user id and add it to the profile_workspace junction table.
export async function POST(
  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 req_data = await req.json();
    const email = String(req_data.email);

    const user = await prisma.profile.findFirst({
      where: {
        email,
      },
    });

    if (!user) {
      return NextResponse.json(
        { error: "User does not exist" },
        { status: 500 }
      );
    }

    await prisma.profile_workspace.create({
      data: {
        profile_id: user.id,
        workspace_id: BigInt(workspaceID),
      },
    });

    const projects = await prisma.project.findMany({
      where: {
        workspace_id: BigInt(workspaceID),
      },
    });

    // Add the user to all projects within the workspace
    for (const project of projects) {
      await prisma.profile_project.create({
        data: {
          profile_id: user.id,
          project_id: project.id,
        },
      });
    }

    return NextResponse.json({ message: "Success!" }, { status: 200 });
  } catch (err) {
    console.error(err);
    return NextResponse.json({ error: err }, { status: 500 });
  }
}