import { getSession } from "@auth/solid-start";
import { APIEvent } from "@solidjs/start/server/types";
import { eq } from "drizzle-orm";
import createClient from "openapi-fetch";
import db from "~/drizzle";
import { accounts } from "~/drizzle/schema";
import { authOptions } from "~/server/auth";
import { paths } from "~/types/discord";

type data = {
  success: boolean | null;
  guilds: {
    id: string;
    name: string;
    icon: string | null | undefined;
  }[];
};

export const GET = async (
  event: APIEvent,
): Promise<
  { success: false; message: string } | (data & { success: true })
> => {
  if (!event) return { success: false, message: "No request event!" };

  const session = await getSession(event.request, authOptions);
  if (!session?.user?.id)
    return { success: false, message: "No user with id!" };

  const { DISCORD_ACCESS_TOKEN } = (
    await db
      .selectDistinct({ DISCORD_ACCESS_TOKEN: accounts.access_token })
      .from(accounts)
      .where(eq(accounts.userId, session.user?.id))
      .limit(1)
      .execute()
  )[0];
  if (!DISCORD_ACCESS_TOKEN)
    return { success: false, message: "No discord access token!" };

  const { GET } = createClient<paths>({
    baseUrl: "https://discord.com/api/v10",
  });
  const { data: guilds, error } = await GET("/users/@me/guilds", {
    headers: { Authorization: `Bearer ${DISCORD_ACCESS_TOKEN}` },
  });

  console.log("guilds", guilds);

  if (error) {
    console.log(error);
    return { success: false, message: "Error on discord api request!" };
  }

  return {
    success: true,
    guilds:
      guilds
        ?.filter((e) => parseInt(e.permissions) & (1 << 5))
        .map(({ id, name, icon }) => ({ id, name, icon })) ?? [],
  };
};
