const mongoose = require("mongoose");

// const dbConnection =require('../config/config.js');
// mongoose.connection = dbConnection;
// const { schema } = require('./Asset');

const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;

// Store a random password reset code
const code = Math.floor(100000 + Math.random() * 900000);
const RoleSchema = new Schema({ name: String });

const CounterSchema = new mongoose.Schema({
  _id: { type: String, required: true },
  seq: { type: Number, default: 0 }
});

const resetCounter = async () => {
  await Counter.findOneAndUpdate({ _id: 'booking_id' }, { seq: 0 });
};


const generateCustomerId = async () => {
  var result = await Counter.findOneAndUpdate(
    { _id: 'customer_id' },
    { $inc: { seq: 1 } },
    { upsert: true, new: true }
  );

  return result.seq;
};

const generateBookingId = async () => {
  var result = await Counter.findOneAndUpdate(
    { _id: 'booking_id' },
    { $inc: { seq: 1 } },
    { upsert: true, new: true }
  );

  return result.seq;
};





const userSchema = new mongoose.Schema(
  {
    installationId:{type:String},
    username: { type: String },
    phone: { type: String, unique: true, trim: true },
    address: String,
    customerId: { type: String },
    buildingName: String,
    inchargeName: String,   
    phoneVerified: { type: Boolean, default: false },
    phoneVerificationCode: { type: Number, default: 11111 },
    passwordResetCode: { type: Number, default: code },
    oneTimePasswordSetFlag: { type: Boolean, default: false },
    emails: [{ email: String, verified: { type: Boolean, default: false } }],
    services: { password: { bcrypt: String } },
    survey_status:{ type:String,default: "pending" },   
    staff: {
    
      
      staff: [
        {
          name: { type: String },
          phone: { type: String },
          all_motor_access: { type: String },
          password: { type: String, default: null },
          
          status: { type: String, default: "active" },
          
         
        }
      ],
    
    
    },
    profile: {
      role: [{ type: String, default: "user" }],
      firstName: { type: String, default: null },
      lastName: { type: String, default: null },
      contactNumber: { type: String, default: null },
      address1: { type: String, default: null },
      address2: { type: String, default: null },
      city: { type: String, default: null },
      state: { type: String, default: null },
      country: { type: String, default: null },
      zip: { type: String, default: null },
      notes: { type: String, default: null },
    },

    stripeCustomerId: String,
    stripePaymentIntentId: String,
    stripeSubscriptionId: String,
    stripeSubscriptionStatus: { type: Boolean, default: false },
    stripePaymentStatus: { type: Boolean, default: false },
    stripePlanId: String,
    stripeAmountReceived: Number,
    stripeSubscripedOn: { type: Date },
    stripeCancelledOn: { type: Date },
    stripeData: Object,
    notes: String,
    currentGPS: {
      // It's important to define type within type field, because
      // mongoose use "type" to identify field's object type.

      gpsType: { type: String, default: "Point" },
      // Default value is needed. Mongoose pass an empty array to
      // array type by default, but it will fail MongoDB's pre-save
      // validation.
      coordinates: { type: [Number], default: [0, 0] },
    },

    longitude: { type : Number,default: 0.0},
    latitude: {type: Number,default: 0.0},
    isActive: Boolean,
    tenantId: ObjectId,
    // fcmId: { type: String, default: null },
    fcmIds: [{ type: String }], // Changed to an array of strings

    deviceId: { type: String, default: null },
    notificationPreference: {
      type: String,
      enum: ["never", "always", "6_hours", "8_hours", "1_month"],
      default: "always", // Default is now "always"
    },
    lastNotificationSent: {
      type: Date,
      default: null, // Initially, no notifications sent
    },
    notificationTime: { type: String }, 
    allowNotifications: { type: Boolean, default: true },
    lowWaterAlert: { type: Boolean, default: true },
    criticalLowWaterAlert: { type: Boolean, default: true },
    manualStartAndStopNotify: { type: Boolean, default: true },
    automaticStartAndStopNotify: { type: Boolean, default: true },


    createdAt: {
      type: Date,
      default: function () {
        return Date.now();
      },
    },
    createdBy: ObjectId,
    updatedAt: {
      type: Date,
      default: function () {
        return Date.now();
      },
    },
    updatedBy: ObjectId, 
  },
  { versionKey: false }
);
 
const profilePictureSchema = new Schema({
  customerId: {
    type: String,
    unique: true,
    required: true
  },
  picture: {
    type: String, // Change the type to String
    required: true,
    validate: {
      validator: function (value) {
        const supportedFormats = ['jpg', 'jpeg', 'png'];
        const fileExtension = value.split('.').pop().toLowerCase();
        return supportedFormats.includes(fileExtension);
      },
      message: 'Picture must be a JPEG, PNG, or JPG image'
    }
  }
});

const teamMembersSchema = new mongoose.Schema({
  customerId:{ type: String, default: null },
  teamAdminName:{ type: String, default: null },
  name: { type: String, default: null },
  phone: { type: String, default: null,unique:true },  
  alternativeContactNumber : { type : String,default: null },
  phoneVerified: { type: Boolean, default: false },
  phoneVerificationCode: { type: Number, default: 11111 },
  passwordResetCode: { type: Number, default: code },
  oneTimePasswordSetFlag: { type: Boolean, default: false },  
  fcmId: { type: String, default: null },
});


const ProfilePicture = mongoose.model('ProfilePicture', profilePictureSchema);
const Counter = mongoose.model('Counter', CounterSchema);
const User = mongoose.model("User", userSchema);
const AddTeamMembers = mongoose.model("AddTeamMembers", teamMembersSchema);

  
// Exporting our model objects



//module.exports = mongoose.model("User", userSchema);

module.exports = { User,Counter, generateCustomerId,generateBookingId ,resetCounter,ProfilePicture,AddTeamMembers};
