import { doc } from "../firebase";

export interface ProfileQrPayload {
  type: "AMBA_PROFILE";
  version: 1;
  accountId: string;
  name: string;
  phoneNumber: string;
}

export class UserQrService {
  static async getOrCreateProfileQr(params: {
    uid: string;
    accountId: string;
    name: string;
    phoneNumber: string;
  }): Promise<string> {
    const { uid, accountId, name, phoneNumber } = params;

    try {
      const userRef = doc("users", uid);
      const snap = await userRef.get();
      const data = snap?.data ? snap.data() : undefined;
      const existingQr: unknown = data?.qrCode;

      if (typeof existingQr === "string" && existingQr.length > 0) {
        return existingQr;
      }

      const payload: ProfileQrPayload = {
        type: "AMBA_PROFILE",
        version: 1,
        accountId,
        name,
        phoneNumber,
      };
      const payloadString = JSON.stringify(payload);

      try {
        await userRef.update({ qrCode: payloadString });
      } catch (error) {
        console.warn(
          "[UserQrService] Failed to persist qrCode field for user",
          uid,
          error
        );
      }

      return payloadString;
    } catch (error) {
      console.error("[UserQrService] getOrCreateProfileQr error", error);
      const fallback: ProfileQrPayload = {
        type: "AMBA_PROFILE",
        version: 1,
        accountId: params.accountId,
        name: params.name,
        phoneNumber: params.phoneNumber,
      };
      return JSON.stringify(fallback);
    }
  }
}

export default UserQrService;
