// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import KimapClient from "hyperware-login";
import { NextRequest } from "next/server";

type Data =
  | {
      ok: boolean;
    }
  | { error: string };

export async function POST(req: NextRequest) {
  try {
    const { node, message, signature } = await req.json();
    console.log({ node, message, signature });
    const kimap = new KimapClient(process.env.BASESCAN_API_KEY!);
    const verificationResponse = await kimap.verifySignature(
      node,
      message,
      signature,
    );
    console.log({ verificationResponse });
    if ("error" in verificationResponse)
      return Response.json(verificationResponse, { status: 500 });
    else {
      // const isGud = true;
      const isGud = verificationResponse.ok;
      if (isGud) {
        // generate some cookie-ish string here
        const auth = "henlo";
        const authToken = `${node}:${auth}`;

        return Response.json(
          { ok: isGud },
          { headers: { "x-hyperware-auth": authToken } },
        );
      }
      return Response.json({ error: "invalid signature" });
    }
  } catch (e) {
    return Response.json({ error: "bad request" }, { status: 500 });
  }
}
