import { createClient } from "@supabase/supabase-js";
import { Database } from "../../lib/database.types";
import { z } from "zod";
import {
  getSessionFromCookie,
  isValidBody,
} from "../../lib/edge-runtime/utils";
import { NextRequest, NextResponse } from "next/server";

export const config = {
  runtime: "edge",
};

if (process.env.SERVICE_LEVEL_KEY_SUPABASE === undefined) {
  throw new Error("SERVICE_LEVEL_KEY_SUPABASE is not defined!");
}

if (process.env.NEXT_PUBLIC_SUPABASE_URL === undefined) {
  throw new Error("NEXT_PUBLIC_SUPABASE_URL is not defined!");
}

const supabase = createClient<Database>(
  process.env.API_SUPABASE_URL ?? process.env.NEXT_PUBLIC_SUPABASE_URL,
  process.env.SERVICE_LEVEL_KEY_SUPABASE,
  {
    auth: {
      persistSession: false,
    },
  },
);

const JoinOrgZod = z.object({ join_id: z.string() }).strict();
type JoinOrgType = z.infer<typeof JoinOrgZod>;

const headers = {
  "Content-type": "application/json",
  "Cache-control": "no-store",
};

export default async function handler(req: NextRequest) {
  if (req.method !== "POST") {
    return new Response(
      JSON.stringify({
        error: "Only POST requests allowed",
      }),
      { status: 405, headers },
    );
  }
  if (!isValidBody<JoinOrgType>(req.body, JoinOrgZod)) {
    return new Response(JSON.stringify({ message: "Invalid request body" }), {
      status: 400,
      headers,
    });
  }
  const { session } = await getSessionFromCookie(req);
  if (!session) {
    return new Response(JSON.stringify({ error: "Unauthorized" }), {
      status: 401,
      headers,
    });
  }

  const { data, error } = await supabase
    .from("organizations")
    .select("id")
    .eq("join_link_id", req.body.join_id);
  if (error) throw new Error(error.message);
  if (data === null) {
    throw new Error("No data returned from organizations insert");
  }

  const profileResp = await supabase
    .from("profiles")
    .update({ org_id: data[0].id })
    .eq("id", session.user.id)
    .select();
  if (profileResp.error) throw profileResp.error;
  if (profileResp.data === null)
    throw new Error("No data returned from profiles update");

  return new Response(JSON.stringify({ success: true }), {
    status: 200,
    headers,
  });
}
