import { db, JudgementTable } from "@/lib/mastoauth/kysely";
import { nanoid } from "nanoid";
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)
    .select('id')
    .executeTakeFirst();

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

  const until = parseInt(request.nextUrl.searchParams.get("until") || Date.now().toString());
  let judgement = await db
    .selectFrom('judgements')
    .where('judgements.content_id', '=', id)
    .where('judgements.published', '<', until)
    .limit(20)
    .orderBy('judgements.published', 'desc')
    .selectAll()
    .execute();

  if (judgement == null) return new Response('', {
    status: 500
  });

  return Response.json(judgement);
}

export async function POST(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)
    .select(['id', 'jam_id'])
    .executeTakeFirst();

  if (content == null) return new Response('', {
    status: 404
  });
  
  // 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(['id', 'banned'])
    .executeTakeFirst();

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

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

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

  const te = [];
  if (body.id != null) te.push("id");
  if (body.author_id != null) te.push("author_id");
  if (body.content_id != null) te.push("content_id");
  if (typeof body.content !== 'string' || body.content.length < 10 || body.content.length > 10000) te.push("content");
  if (body.published != null) te.push("published");
  

  if (te.length > 0) return new Response(JSON.stringify(te, null, 2), {
    status: 400
  })

  let newBody:JudgementTable = body;

  let curBody = {
    id: nanoid(21),
    author_id: existingUser.id,
    content_id: content.id,
    content: newBody.content,
    published: Date.now()
  };

  let res;
  try {
    res = await db
      .insertInto('judgements')
      .values(curBody)
      .executeTakeFirstOrThrow();
  } catch (err) {
    return new Response('', {
      status: 500
    });
  }

  return new Response(curBody.id, {
    status: 200
  });
}