import { APIEvent } from "@solidjs/start/server";
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/{guildId}/config";

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
    .findFirst({
      where: eq(guilds.id, guildId),
      with: { tpMessages: true, matches: true },
    })
    .execute();

  if (!guildQuery) return ErrorResponse("NOT_FOUND");

  return Res("OK", buildConfig(guildQuery));
};

export const POST = async (
  event: APIEvent,
): Promise<APIResponse<Path, "post">> => {
  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.insert(guilds).values({ id: guildId }).execute();

  if (!guildQuery) return ErrorResponse("NOT_FOUND");

  return Res("NO_CONTENT", null);
};

export const DELETE = async (
  event: APIEvent,
): Promise<APIResponse<Path, "delete">> => {
  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
    .findFirst({
      where: eq(guilds.id, guildId),
      with: { tpMessages: true, matches: true },
    })
    .execute();

  if (!guildQuery) return ErrorResponse("NOT_FOUND");

  await db.delete(guilds).where(eq(guilds.id, guildId)).execute();

  return Res("NO_CONTENT", null);
};
