import { createServerComponentClient } from "@supabase/auth-helpers-nextjs";
import { Database } from "@/types/supabase";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { NextResponse, NextRequest } from "next/server";
import prisma from "@/lib/prisma";
import { WorkspaceSidebar } from "@/components/workspace-sidebar";

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

async function getWorkspace(workspaceID: string) {
  const supabase = createServerComponentClient<Database>({ cookies });
  const session = await getSession(supabase);

  if (!session) redirect("/auth");

  try {
    // TODO: get workspace by workspaceID if user is part of the workspace
    return NextResponse.json({}, { status: 200 });
  } catch (err: any) {
    console.error(err);
    return NextResponse.json(
      { error: "Something went wrong." },
      { status: 500 }
    );
  }
}

export default async function Workspace({
  params: { workspaceID },
}: {
  params: { workspaceID: string };
}) {
  const raw_workspace = await getWorkspace(workspaceID);
  const workspace = await raw_workspace.json();

  if (workspace.error == "not_found") {
    return (
      <div>
        <h1>Workspace not found.</h1>
      </div>
    );
  } else if (workspace.error == "unauthorized") {
    return (
      <div>
        <h1>You are not a member of this workspace.</h1>
      </div>
    );
  } else if (workspace.error) {
    return (
      <div>
        <h1>Something went wrong.</h1>
      </div>
    );
  }

  return (
    <div className="flex flex-row">
      <WorkspaceSidebar workspaceID={workspaceID} />
      <h1>Workspace Page</h1>
    </div>
  );
}
