import { ContentTable, db, JamTable } 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: {jam: string}}) {
  const id = params.jam;
  if (id == null) return new Response('', {
    status: 400
  });
  let jam = await db
    .selectFrom('jams')
    .where('jams.id', '=', id)
    .select('id')
    .executeTakeFirst();

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

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

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

  return Response.json(content);
}

export async function POST(request: NextRequest, {params}: {params: {jam: string}}) {
  const id = params.jam;
  if (id == null) return new Response('', {
    status: 400
  });
  let jam = await db
    .selectFrom('jams')
    .where('jams.id', '=', id)
    .select(['id', 'date_start', 'date_end'])
    .executeTakeFirst();

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

  const currentDate = Date.now();

  if (currentDate <= jam.date_start || currentDate >= jam.date_end) return new Response('', {
    status: 403
  });
  
  // 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.jam_id != null) te.push("jam_id");
  if (typeof body.name !== 'string' || body.name.length < 10 || body.name.length > 2048) te.push("name");
  if (typeof body.description !== 'string' || body.description.length < 10 || body.description.length > 10000) te.push("description");
  if (typeof body.url !== 'string' || body.url.length < 3 || body.url.length > 2048) te.push("url");
  if (body.submitted != null) te.push("submitted");
  if (body.winner != null) te.push("winner");
  

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

  let newBody:ContentTable = body;

  let curBody = {
    id: nanoid(21),
    author_id: existingUser.id,
    jam_id: id,
    name: newBody.name,
    description: newBody.description,
    url: newBody.url,
    submitted: Date.now(),
    winner: false
  };

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

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