import { TFAType } from "@hibas123/openauth-internalapi";
import DB from "../database.js";
import { ModelDataBase } from "@hibas123/safe_mongo/lib/model.js";
import { ObjectId } from "bson";
import { Binary } from "mongodb";

export { TFAType as TFATypes };


export const TFANames = new Map<TFAType, string>();
TFANames.set(TFAType.TOTP, "Authenticator");
TFANames.set(TFAType.BACKUP_CODE, "Backup Codes");
TFANames.set(TFAType.WEBAUTHN, "Security Key (WebAuthn)");
TFANames.set(TFAType.APP_ALLOW, "App Push");

export interface ITwoFactor extends ModelDataBase {
   user: ObjectId;
   valid: boolean;
   expires?: Date;
   name?: string;
   type: TFAType;
   data: any;
}

export interface ITOTP extends ITwoFactor {
   data: string;
}

export interface IWebAuthn extends ITwoFactor {
   data: {
      challenge?: any;
      device?: {
         credentialID: Binary | string;
         credentialPublicKey: Binary;
         counter: number;
         transports: AuthenticatorTransport[]
      }
   };
}

export interface IU2F extends ITwoFactor {
   data: {
      challenge?: string;
      publicKey: string;
      keyHandle: string;
      registration?: string;
   };
}

export interface IBackupCode extends ITwoFactor {
   data: string[];
}

const TwoFactor = DB.addModel<ITwoFactor>({
   name: "twofactor",
   versions: [
      {
         migration: (e) => { },
         schema: {
            user: { type: ObjectId },
            valid: { type: Boolean },
            expires: { type: Date, optional: true },
            name: { type: String, optional: true },
            type: { type: Number },
            data: { type: "any" },
         },
      },
   ],
});

export default TwoFactor;
