import { APIEvent } from "@solidjs/start/server/types";
import { eq } from "drizzle-orm";
import db from "~/drizzle";
import { guilds } from "~/drizzle/schema";
import { BasicAuth } from "~/lib/auth";
import { buildConfig } from "~/lib/responseBuilders";
import { ErrorResponse, Res } from "~/lib/responses";
import { zodBigIntId } from "~/lib/zod";
import { APIResponse } from "~/types/backend";

type Path = "/api/boot";

export const GET = async (
  event: APIEvent,
): Promise<APIResponse<Path, "get">> => {
  switch (event.request.headers.get("authorization")) {
    case BasicAuth.unencoded:
    case BasicAuth.encoded:
      break;

    default:
      return ErrorResponse("UNAUTHORIZED");
  }

  let guildId: bigint;
  try {
    guildId = zodBigIntId.parse(event.params.guildId);
  } catch (e) {
    return ErrorResponse("BAD_REQUEST", JSON.stringify(e));
  }

  const guildQuery = await db.query.guilds
    .findMany({
      where: eq(guilds.id, guildId),
      with: { tpMessages: true, matches: true },
    })
    .execute();

  return Res(
    "OK",
    guildQuery.map((e) => buildConfig(e)),
  );
};
