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

export async function GET(request: NextRequest) {
  const cookieStore = cookies();
  const instance = request.nextUrl.searchParams.get("instance");
  if (instance == null) return new Response('', {
    status: 400
  });
  const mauth = new MastoAuth(instance);

  // Check if instance is fediblocked

  const fnListRequest = await fetch("https://seirdy.one/pb/FediNuke.txt");
  
  const fnList = await fnListRequest.text();

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

  const ssListRequest = await fetch("https://seirdy.one/pb/spammy-subdomains.txt");
  
  const ssList = await ssListRequest.text();

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

  // Split lists

  const JSONFnList = fnList.split("\n");
  const JSONSsList = ssList.split("\n");

  if (JSONSsList.includes(instance)) return new Response('https://seirdy.one/pb/spammy-subdomains.txt', {
    status: 403
  });

  if (JSONFnList.includes(instance)) return new Response('https://seirdy.one/pb/FediNuke.txt', {
    status: 403
  });

  // Check if instance app exists
  // For github.com, it should
  let existingInstanceApp = await db
      .selectFrom('apps')
      .where('apps.instance_domain', '=', instance)
      .selectAll()
      .executeTakeFirst();

  console.log(instance);

  if (existingInstanceApp == null) {
    // Create new app
    const temp_iapp = await mauth.newApplication();

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

    existingInstanceApp = {
      instance_domain: instance,
      client_id: temp_iapp.client_id,
      client_secret: temp_iapp.client_secret,
      redirect_uri: temp_iapp.redirect_uri
    } as AppTable;

    try {
      await db.insertInto('apps')
        .values(existingInstanceApp)
        .returningAll()
        .executeTakeFirstOrThrow();
    } catch (err) {
      return new Response('', {
        status: 500
      });
    }
  }

  cookieStore.set("instance", instance, {
    expires: Date.now() + 604800000
  });
  if (instance == "discord.com")
    return Response.redirect(`https://${instance}/oauth2/authorize?response_type=code&client_id=${existingInstanceApp.client_id}&redirect_uri=${existingInstanceApp.redirect_uri}&scope=identify&state=${Math.random().toString(36).slice(2)}&integration_type=1`)
  if (instance == "github.com")
    return Response.redirect(`https://${instance}/login/oauth/authorize?client_id=${existingInstanceApp.client_id}&redirect_uri=${existingInstanceApp.redirect_uri}&scope=&state=${Math.random().toString(36).slice(2)}`)
  return Response.redirect(`https://${instance}/oauth/authorize?response_type=code&client_id=${existingInstanceApp.client_id}&redirect_uri=${existingInstanceApp.redirect_uri}&scope=read`);
}