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

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

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

  return Response.json(content);
}

export async function PATCH(request: NextRequest, {params}: {params: {content: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 id = params.content;

  if (id == null) return new Response('', {
    status: 400
  });
  
  let updatingContent = await db
  .selectFrom('content')
  .where('content.id', '=', id)
  .select(['author_id'])
  .executeTakeFirst();

  console.log(updatingContent, existingUser)

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

  if (!existingUser?.admin && updatingContent.author_id != existingUser.id) 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<ContentTable> = {};

  if (body.name != null && typeof body.name === 'string' && body.name.length >= 10 && body.name.length <= 2048) newBody.name = body.name;
  if (body.description != null && typeof body.description === 'string' && body.description.length >= 10 && body.description.length <= 10000) newBody.description = body.description;
  if (body.url != null && typeof body.url === 'string' && body.url.length >= 3 && body.url.length <= 2048) newBody.url = body.url;
  if (body.winner != null && typeof body.winner === 'boolean' && existingUser?.admin) newBody.winner = body.winner;

  console.log(body, newBody);
  
  let res;
  try {
    res = await db
      .updateTable('content')
      .set(newBody)
      .where('id', '=', id)
      .executeTakeFirstOrThrow();
  } catch (err) {
    return new Response('', {
      status: 500
    });
  }

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

export async function DELETE(request: NextRequest, {params}: {params: {content: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 id = params.content;

  if (id == null) return new Response('', {
    status: 400
  });
  
  let deletingContent = await db
  .selectFrom('content')
  .where('content.id', '=', id)
  .select(['author_id', 'jam_id'])
  .executeTakeFirst();

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

  console.log(deletingContent, existingUser)

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

  let jamParentOwner, jamParent = await db
    .selectFrom('jams')
    .where('jams.id', '=', deletingContent.jam_id)
    .select('author_id')
    .executeTakeFirst();

  if (jamParent != null) {
    jamParentOwner = await db
      .selectFrom('users')
      .where('users.id', '=', jamParent.author_id)
      .select('id')
      .executeTakeFirst();
  }

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

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

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

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