// Connections
import mongoConnection from "$connections/mongo/mongo.connection.js";

import mongoose from "mongoose";
const mongooseSchema = mongoose.Schema;

export const schemaModel = {
  nationalId: {
    type: String,
    unique: true,
    sparse: true, // Allows null values while maintaining uniqueness
    required: false,
  },
  businessID: {
    type: String,
    unique: true,
    sparse: true,
    required: false,
  },
  role: {
    type: mongooseSchema.Types.ObjectId,
    ref: "Role",
    default: null,
  },
  accessGrants: {
    type: [String],
    default: [],
  },
  fullName: {
    type: String,
    default: "",
  },
  mobile: {
    type: String,
    default: "",
  },
  isPrivatePerson: {
    type: Boolean,
    default: true,
  },
  isSejamVerified: {
    type: Boolean,
    default: false,
  },
  isTadbirVerified: {
    type: Boolean,
    default: false,
  },
  isSepahVerified: {
    type: Boolean,
    default: false,
  },
  telegramId: {
    type: String,
    unique: true,
    sparse: true,
    trim: true,
    default: undefined,
  },
  isTelegramVerified: {
    type: Boolean,
    default: false,
    index: true,
  },
  telegramVerifiedAt: {
    type: Date,
    default: null,
  },
  clubReferralCode: {
    type: String,
    unique: true,
    sparse: true,
    trim: true,
    default: undefined,
  },
  clubInviter: {
    type: mongooseSchema.Types.ObjectId,
    ref: "User",
    default: null,
    index: true,
  },
  clubSuccessfulReferralCount: {
    type: Number,
    default: 0,
  },
};

export const schema = new mongooseSchema(schemaModel, { timestamps: true });

schema.path("clubReferralCode").set((value) => {
  const normalizedValue = String(value || "")
    .trim()
    .toUpperCase();
  return normalizedValue || undefined;
});

export default mongoConnection.model("User", schema);
