import axios from "axios";
import * as didJwt from "did-jwt";
import { AppString } from "@/constants/app";
import { db } from "../db";
import { SERVICE_ID } from "../libs/endorserServer";
import { deriveAddress, newIdentifier } from "../libs/crypto";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";

/**
 * Get User #0 to sign & submit a RegisterAction for the user's activeDid.
 */
export async function testServerRegisterUser() {
  const testUser0Mnem =
    "seminar accuse mystery assist delay law thing deal image undo guard initial shallow wrestle list fragile borrow velvet tomorrow awake explain test offer control";

  const [addr, privateHex, publicHex, deriPath] = deriveAddress(testUser0Mnem);

  const identity0 = newIdentifier(addr, publicHex, privateHex, deriPath);

  await db.open();
  const settings = await db.settings.get(MASTER_SETTINGS_KEY);

  // Make a claim
  const vcClaim = {
    "@context": "https://schema.org",
    "@type": "RegisterAction",
    agent: { did: identity0.did },
    object: SERVICE_ID,
    participant: { did: settings?.activeDid },
  };
  // Make a payload for the claim
  const vcPayload = {
    sub: "RegisterAction",
    vc: {
      "@context": ["https://www.w3.org/2018/credentials/v1"],
      type: ["VerifiableCredential"],
      credentialSubject: vcClaim,
    },
  };
  // create a signature using private key of identity
  // eslint-disable-next-line
  const privateKeyHex: string = identity0.keys[0].privateKeyHex!;
  const signer = await didJwt.SimpleSigner(privateKeyHex);
  const alg = undefined;
  // create a JWT for the request
  const vcJwt: string = await didJwt.createJWT(vcPayload, {
    alg: alg,
    issuer: identity0.did,
    signer: signer,
  });

  // Make the xhr request payload

  const payload = JSON.stringify({ jwtEncoded: vcJwt });
  const endorserApiServer =
    settings?.apiServer || AppString.TEST_ENDORSER_API_SERVER;
  const url = endorserApiServer + "/api/claim";
  const headers = {
    "Content-Type": "application/json",
  };

  const resp = await axios.post(url, payload, { headers });
  console.log("User registration result:", resp);
}
