import { db, UserTable } from "@/lib/mastoauth/kysely";
import { cookies } from "next/headers";
import { NextRequest } from "next/server";

export async function GET(request: NextRequest, {params}: {params: {user:string}}) {
  const name = params.user;
  if (name == null) return new Response('', {
    status: 400
  });
  let user = await db
    .selectFrom('users')
    .where('users.id', '=', name)
    .selectAll()
    .executeTakeFirst();

  if (user == null) return new Response('', {
    status: 404
  });

  return Response.json(user);
}

export async function PATCH(request: NextRequest, {params}: {params: {user:string}}) {
  // verify user
  const cookieStore = cookies();
  const token = cookieStore.get('token')?.value;

  if (token == null) return new Response('', {
    status: 401
  });

  let existingToken = await db
    .selectFrom('tokens')
    .where('tokens.id', '=', token)
    .select('owner')
    .executeTakeFirst();

  if (existingToken == null) return new Response('', {
    status: 401
  });

  let existingUser = await db
    .selectFrom('users')
    .where('users.id', '=', existingToken.owner)
    .select(['admin', 'id', 'banned'])
    .executeTakeFirst();

  if (existingUser == null) return new Response('', {
    status: 401
  });

  if (existingUser.banned) return new Response('U banned motherfucka!', {
    status: 403
  });

  const name = params.user;

  if (name == null) return new Response('', {
    status: 400
  });

  let updatingUser = await db
    .selectFrom('users')
    .where('users.id', '=', name)
    .select('id')
    .executeTakeFirst();

  if (updatingUser == null) return new Response('', {
    status: 400
  });

  if (!existingUser?.admin) return new Response('you are NOT that guy.', {
    status: 401
  });

  let body;
  try { 
    body = await request.json();
  } catch (err) {
    return new Response('', {
      status: 400
    })
  }

  let newBody:Partial<UserTable> = {};

  if (body.admin != null && typeof body.admin === 'boolean') newBody.admin = body.admin;
  if (body.banned != null && typeof body.banned === 'boolean') newBody.banned = body.banned;
  
  let res;
  try {
    res = await db
      .updateTable('users')
      .set(newBody)
      .where('users.id', '=', updatingUser.id)
      .executeTakeFirstOrThrow();
  } catch (err) {
    return new Response('', {
      status: 500
    });
  }

  return new Response(null, {
    status: 204
  })
}

export async function DELETE(request: NextRequest, {params}: {params: {user:string}}) {
  // verify user
  const cookieStore = cookies();
  const token = cookieStore.get('token')?.value;

  if (token == null) return new Response('', {
    status: 401
  });

  let existingToken = await db
    .selectFrom('tokens')
    .where('tokens.id', '=', token)
    .select('owner')
    .executeTakeFirst();

  if (existingToken == null) return new Response('', {
    status: 401
  });

  let existingUser = await db
    .selectFrom('users')
    .where('users.id', '=', existingToken.owner)
    .select(['admin', 'id', 'banned'])
    .executeTakeFirst();

  if (existingUser == null) return new Response('', {
    status: 401
  });

  if (existingUser.banned) return new Response('U banned motherfucka!', {
    status: 403
  });

  const name = params.user;

  if (name == null) return new Response('', {
    status: 400
  });
  
  let deletingUser = await db
    .selectFrom('users')
    .where('users.id', '=', name)
    .select('id')
    .executeTakeFirst();

  console.log(deletingUser, existingUser)

  if (deletingUser == null) return new Response('', {
    status: 400
  });

  if (!existingUser?.admin && deletingUser.id != existingUser.id) return new Response('you are NOT that guy.', {
    status: 401
  });

  try {
  await db
    .deleteFrom('jams')
    .where('jams.author_id', '=', deletingUser.id)
    .execute();
  } catch (err) {
  }

  try {
  await db
    .deleteFrom('content')
    .where('content.author_id', '=', deletingUser.id)
    .execute();
  } catch (err) {
  }

  try {
  await db
    .deleteFrom('judgements')
    .where('judgements.author_id', '=', deletingUser.id)
    .execute();
  } catch (err) {
  }

  try {
    await db
      .deleteFrom('users')
      .where('users.id', '=', deletingUser.id)
      .executeTakeFirstOrThrow();
  } catch (err) {
    return new Response('', {
      status: 500
    });
  }

  return new Response(null, {
    status: 204
  });
}