import axios from "axios";
import * as didJwt from "did-jwt";
import { SERVICE_ID } from "../libs/endorserServer";
import {
  DEFAULT_ROOT_DERIVATION_PATH,
  deriveAddress,
  newIdentifier,
} from "../libs/crypto";
import { logger } from "../utils/logger";
import { AppString } from "../constants/app";
import { saveNewIdentity } from "@/libs/util";
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";

const TEST_USER_0_MNEMONIC =
  "rigid shrug mobile smart veteran half all pond toilet brave review universe ship congress found yard skate elite apology jar uniform subway slender luggage";

export async function testBecomeUser0() {
  const [addr, privateHex, publicHex, deriPath] =
    deriveAddress(TEST_USER_0_MNEMONIC);

  const identity0 = newIdentifier(addr, publicHex, privateHex, deriPath);
  await saveNewIdentity(
    identity0,
    TEST_USER_0_MNEMONIC,
    DEFAULT_ROOT_DERIVATION_PATH,
  );
  const platformService = await PlatformServiceFactory.getInstance();
  await platformService.updateDidSpecificSettings(identity0.did, {
    isRegistered: true,
  });
}

/**
 * Get User #0 to sign & submit a RegisterAction for the user's activeDid.
 *
 * This test function demonstrates the registration process for a user with the endorser server.
 * It creates a verifiable credential claim and submits it via JWT to the endorser API.
 *
 * @returns Promise<void> - Completes when registration is successful
 * @throws Error if registration fails or database access fails
 */
export async function testServerRegisterUser() {
  const [addr, privateHex, publicHex, deriPath] =
    deriveAddress(TEST_USER_0_MNEMONIC);

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

  // Use dynamic import for database access in test context
  const { retrieveSettingsForActiveAccount } = await import(
    "@/db/databaseUtil"
  );
  const settings = await retrieveSettingsForActiveAccount();

  // Make a claim
  const vcClaim = {
    "@context": "https://schema.org",
    "@type": "RegisterAction",
    agent: { identifier: identity0.did },
    object: SERVICE_ID,
    participant: { identifier: 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 });
  logger.log("User registration result:", resp);
  return resp;
}
