const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;
const { Counter} = require('../models/User')
const code = Math.floor(100000 + Math.random() * 900000);


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

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

const installationschema = new mongoose.Schema({
   // name: { type: String },
    phone: { type: String, unique: true, trim: true },
    address: String,
    installationId: { type: String }, 
    phoneVerified: { type: Boolean, default: false },
    phoneVerificationCode: { type: Number, default: 11111 },
    passwordResetCode: { type: Number},
    oneTimePasswordSetFlag: { type: Boolean, default: false },
    emails: [{ email: String, verified: { type: Boolean, default: false } }],
    services: { password: { bcrypt: String } },
    alternativeNumber: { type: String, default: null },
    firstName: { type: String, default: null },
    lastName: { type: String, default: null },
    address1: { type: String, default: null },
    address2: { type: String, default: null },
    city: { type: String, default: null },
    designation: { type: String, default: null },
    reportingManager: { type: String, default: null },
    departmentName: { type: String, default: null },
    zone: { type: String, default: null },
    type: { type: String },

    profile: {
     
      state: { type: String, default: null },
      country: { type: String, default: null },
    },
   team : {  type: String, default: null},
   manager : {  type: String, default: null},
   team_member: {
      
    team_member: [
      {
        teamMemberId: { type: String }, 
        firstName: { type: String },
        phone: { type: String },
        installationTeamMemId: { type: String },
        password: { type: String, default: null },
        status: { type: String, default: "active" },
        email: { type: String },
        alternativePhone: { type: String },

      }
    ],
  
  
  },
  
    longitude: { type : Number,default: 0.0},
    latitude: {type: Number,default: 0.0},

    fcmId: { type: String, default: null },
    createdAt: {
      type: Date,
      default: function () {
        return Date.now();
      },
    },
    createdBy: ObjectId,
    updatedAt: {
      type: Date,
      default: function () {
        return Date.now();
      },
    },
    updatedBy: ObjectId, 
  
  });


  const surveyschema = new mongoose.Schema({
    // name: { type: String },
     phone: { type: String, unique: true, trim: true },
     address: String,
     surveyId: { type: String }, 
     phoneVerified: { type: Boolean, default: false },
     phoneVerificationCode: { type: Number, default: 11111 },
     passwordResetCode: { type: Number},
     oneTimePasswordSetFlag: { type: Boolean, default: false },
     emails: [{ email: String, verified: { type: Boolean, default: false } }],
     services: { password: { bcrypt: String } },
     alternativeNumber: { type: String, default: null },
     firstName: { type: String, default: null },
     lastName: { type: String, default: null },
     address1: { type: String, default: null },
     address2: { type: String, default: null },
     city: { type: String, default: null },
     designation: { type: String, default: null },
     reportingManager: { type: String, default: null },
     departmentName: { type: String, default: null },
     zone: { type: String, default: null },
     type: { type: String },
 
     profile: {
      
       state: { type: String, default: null },
       country: { type: String, default: null },
     },
    team : {  type: String, default: null},
    manager : {  type: String, default: null},
    team_member: {
       
     team_member: [
       {
         survey_teamMemberId: { type: String }, 
         name: { type: String },
         phone: { type: String },
         installationTeamMemId: { type: String },
         password: { type: String, default: null },
         status: { type: String, default: "active" },
         email: { type: String },
         alternativePhone: { type: String },
 
       }
     ],
   
   
   },
   
     longitude: { type : Number,default: 0.0},
     latitude: {type: Number,default: 0.0},
 
     fcmId: { type: String, default: null },
     createdAt: {
       type: Date,
       default: function () {
         return Date.now();
       },
     },
     createdBy: ObjectId,
     updatedAt: {
       type: Date,
       default: function () {
         return Date.now();
       },
     },
     updatedBy: ObjectId, 
   
   });

  const profilePictureInstallSchema = new Schema({
    installationId: {
      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 profilePictureStoreSchema = new Schema({
    storeId: {
      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 storeSchema = new mongoose.Schema({
    storename: { type: String },
    phone: { type: String, unique: true, trim: true },
    contactPersonName: {type: String},
    contactPersonPhone: { type: String, unique: true, trim: true },
    storeId: { type: String, default: null },
    phoneVerified: { type: Boolean, default: false },
    phoneVerificationCode: { type: Number, default: 11111 },
    passwordResetCode: { type: Number, default: 11111 },
    oneTimePasswordSetFlag: { type: Boolean, default: false },
    emails: {type: String},
    designation: { type: String, default: null },
    reportingManager: { type: String, default: null },
    departmentName: { type: String, default: null },
    zone: { type: String, default: null },
    services: { password: { bcrypt: String } },
    description: { type: String, default: null },
    startingPrice: { type: String, default: 0.0 },
    profile: {
      role: [{ type: String, default: "store" }],
      firstName: { type: String, default: null },
      lastName: { type: String, default: null },
      contactNumber: { type: String, default: null },
      alternativeContactNumber: { type: String, default: null },
      store_address: { 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 },
    },
    status: {
      type: String,
      enum: ['inactive', 'active'],
      default: 'active'
    },
    longitude: { type: Number, default: 0.0 },
    latitude: { type: Number, default: 0.0 },
    isActive: Boolean,
    tenantId: ObjectId,
    fcmId: { type: String, default: null },
    createdAt: {
      type: Date,
      default: function () {
        return Date.now();
      },
    },
    createdBy: ObjectId,
    updatedAt: {
      type: Date,
      default: function () {
        return Date.now();
      },
    },
    updatedBy: ObjectId,
  }, { versionKey: false });

  
const waterLeverSensorInSchema = new mongoose.Schema({
  storeId:{ type: String },
  hardwareId: { type: String },
  masterId: { type: String, default: null },
  type: { type: String },
  indate: { type: String },
  hardwareId_company: { type: String },
  qccheck: { type: String, default: null },
  qccheckdate: { type: String, default: null },
  qcby: { type: String, default: null },
  comment: { type: String, default: "0" },
  outforrepairdate: { type: String, default: "0" },
  sendto: { type: String, default: null },
  repairfeedback:{ type: String, default: "0" },
  dateofinstallation: { type: String, default: null },
  installedby: { type: String, default: "0" },
  customerId:{ type: String,default:"0" },
  comments:{ type: String,default:"0" },
 
   
  slaves: {
    source: { type: String },
    tankhardware: [
      {
        tankhardwareId: { type: String },
        slaveId: { type: String, default: null },
        type: { type: String },
        indate: { type: String },
        hardwareId_company: { type: String },
        qccheck: { type: String, default: null },
        qccheckdate: { type: String, default: null },
        qcby: { type: String, default: null },
        comment: { type: String, default: "0" },
        outforrepairdate: { type: String, default: "0" },
        sendto: { type: String, default: null },
        repairfeedback:{ type: String, default: "0" },
        dateofinstallation: { type: String, default: null },
        installedby: { type: String, default: "0" },
        customerId:{ type: String,default:"0" },
        comments:{ type: String,default:"0" },
      }
    ]
  }
});


  
const motorSwitchSensorInSchema = new mongoose.Schema({
  storeId:{ type: String },
  motorId: { type: String },
  masterId: { type: String, default: null },
  type: { type: String },
  indate: { type: String },
  qccheck: { type: String, default: null },
  qccheckdate: { type: String, default: null },
  qcby: { type: String, default: null },
  comment: { type: String, default: "0" },
  outforrepairdate: { type: String, default: "0" },
  sendto: { type: String, default: null },
  repairfeedback:{ type: String, default: "0" },
  dateofinstallation: { type: String, default: null },
  installedby: { type: String, default: "0" },
  customerId:{ type: String,default:"0" },
  comments:{ type: String,default:"0" },
});



const insensorsSchema = new mongoose.Schema({
  storeId: { type: String },
  hardwareId: { type: String, default: null },
  masterId: { type: String, default: null },
  type: { type: String },
  model: { type: String },
  indate: { type: String },
  hardwareId_company: { type: String, default: null },
  qccheck: { type: String, default: null },
  qccheckdate: { type: String, default: null },
  qcby: { type: String, default: null },
  comment: { type: String, default: "0" },
  outforrepairdate: { type: String, default: "0" },
  sendto: { type: String, default: null },
  repairfeedback: { type: String, default: "0" },
  dateofinstallation: { type: String, default: null },
  installedby: { type: String, default: "0" },
  customerId: { type: String, default: "0" },
  comments: { type: String, default: "0" },
  quantity: { type: Number, default: 0 },
  batchno: { type: String, default: null },
  sensor_type: { type: String }, // adding sensor_type field
  status: { type: String, default: "pending" },
  connected_to: { type: String, default: "0" },
  tankName: { type: String, default: "0" },
  tankLocation: { type: Number, default: 0 },
  connected_slave: { type: String, default: null },
  
  quality_check_details: [{
    damage_check: { result: String },
    stickering_check: { result: String },
    power_check: { result: String },
    master_connecting_gsm: { result: String },
    slave_connecting: { result: String },
    motor_starting: {
      result: String,
      steps: [
        { step: Number, result: String }
      ]
    },
    connecting_to_sensor: { result: String },
    connecting_to_slave: { result: String },
    data_sending: { result: String },
    distance_check: {
      result: String,
      steps: [
        { step: Number, result: String }
      ]
    }
  }]
});



const iotpriceSchema = new mongoose.Schema({
  name: { type: String },
  type: { type: String ,default:null},
  cost: { type: Number, default: null },
});

const estimationorderSchema = new mongoose.Schema({
  orderId: { type: String, unique: true, required: true },
  customerId: { type: String, required: true },
  items: { type: Array, required: true },
  estimatedTotal: { type: String, required: true },
  status: { type: String, default: "pending" },
}, { timestamps: true });


const sensorquotationSchema = new mongoose.Schema({
  customerId: { type: String },
  surveyId: { type: String, default: null },
  storeId: { type: String, default: null },
  installationId: { type: String, default: null },
  quatationId: { type: String, default: null },
  masters: { type: String },
  masters_quantity_price: { type: String },
  masters_total_price: { type: String },
  slaves: { type: String },
  sensors: { type: String },
  slaves_quantity_price: { type: String },
  slaves_total_price: { type: String },
  motor_switches: { type: String },
  motor_switches_quantity_price: { type: String },
  motor_switches_total_price: { type: String },
  quote_status: { type: String, default: null },
  quoted_amount: { type: String, default: null },
  comments: { type: String, default: null },
  datetime: { type: String, default: null },
  updated_at: { type: String, default: null },
  
  master_connections: [
    {
      master_name: { type: String, default: null },
      slaves: { type: String, default: null },
     
      tanks: [
        {
          tankName: { type: String, default: null },
          tankLocation: { type: String, default: null },
         
        },
      ],
     
    },
  ],
  electricals: [
    {
      type: { type: String, default: null },
      wire: { type: String, default: null },
      switch: { type: String, default: null },
      text: { type: String, default: null },
      available_quantity: { type: String, default: null },
    },
  ],
  master_type_quantity_price: { type: String, default: null },
  master_available_quantity: { type: String, default: null },
  slave_available_quantity: { type: String, default: null },
  sensor_available_quantity: { type: String, default: null },
  master_type_total_price: { type: String, default: null }, 
  sensor_type_quantity_price: { type: String , default: null},
  sensor_type_total_price: { type: String , default: null}, 
  switch_type_quantity_price: { type: String, default: null },
  switch_type_total_price: { type: String, default: null },
  qutation_total_price: { type: String, default: null },
});





const orderSchema = new mongoose.Schema({
  customerId: { type: String },
  surveyId: { type: String, default: null },
  storeId: { type: String, default: null },
  installationId: { type: String, default: null },
  quatationId: { type: String, default: null },
  masters: { type: String },
  masters_quantity_price: { type: String },
  masters_total_price: { type: String },
  slaves: { type: String },
  sensors: { type: String },
  slaves_quantity_price: { type: String },
  slaves_total_price: { type: String },
  motor_switches: { type: String },
  motor_switches_quantity_price: { type: String },
  motor_switches_total_price: { type: String },
  quote_status: { type: String, default: null },
  quoted_amount: { type: String, default: null },
  comments: { type: String, default: null },
  datetime: { type: String, default: null },
  updated_at: { type: String, default: null },
  assignedTeamMembers: [{ type: String }], 
 
  electricals: [
    {
      type: { type: String, default: null },
      wire: { type: String, default: null },
      switch: { type: String, default: null },
      text: { type: String, default: null },
      available_quantity: { type: String, default: null },
    },
  ],
  master_type_quantity_price: { type: String, default: null },
  master_available_quantity: { type: String, default: null },
  slave_available_quantity: { type: String, default: null },
  sensor_available_quantity: { type: String, default: null },
  master_type_total_price: { type: String, default: null },
  sensor_type_quantity_price: { type: String, default: null },
  sensor_type_total_price: { type: String, default: null },
  switch_type_quantity_price: { type: String, default: null },
  switch_type_total_price: { type: String, default: null },
  qutation_total_price: { type: String, default: null },
  status: { type: String, default: "pending" }, 
  quatation_status: { type: String, default: "pending" }, 

});

const SensorStockSchema = new mongoose.Schema({
  storeId: {
    type: String,
    required: true,
    ref: "Store",
  },
  type: {
    type: String,
    required: true,
    enum: ["master", "slave", "sensor"], // Ensures only valid types
  },
  total_count: {
    type: Number,
    required: true,
    default: 0,
  },
  total_available: {
    type: Number,
    required: true,
    default: 0,
  },
  total_count_before_qc: {
    type: Number,
    required: true,
    default: 0,
  },
  total_blocked: {
    type: Number,
    required: true,
    default: 0,
  },
  total_repair: {
    type: Number,
    required: true,
    default: 0,
  },
  excess_needed: {
    type: Number,
    required: true,
    default: 0,
  },
  total_installed: {
    type: Number,
    required: true,
    default: 0,
  },
}, { timestamps: true });


const hardwareCartSchema = new mongoose.Schema({
  productId: { type: String},
  productName: { type: String },
  description: { type: String, default: null },
  GST: { type: Number, min: 0 },
  unitPrice: { type: Number, min: 0 },
  quantity: { type: Number, min: 1 },
  grandTotal: { type: Number, min: 0 },  
  totalAmount: { type: Number, min: 0 },  // Amount before GST
  serialId: { type: String, default: null },
  category: { type: String, enum: ['slaves', 'master', 'switches'], default: 'slaves' }, 
  discount: { type: Number, default: 0, min: 0 }, 
}, {
  timestamps: true,  
});

const serviceCartSchema = new mongoose.Schema({
  installationId: {type: String},
  productId: { type: String},
  productName: { type: String },
  description: { type: String, default: null },
  GST: { type: Number, min: 0 },
  unitPrice: { type: Number, min: 0 },
  quantity: { type: Number, min: 1 },
  grandTotal: { type: Number, min: 0 },  
  totalAmount: { type: Number, min: 0 },  // Amount before GST
  serialId: { type: String, default: null },
  category: { type: String, enum: ['slaves', 'master', 'switches'], default: 'slaves' }, 
  discount: { type: Number, default: 0, min: 0 }, 
}, {
  timestamps: true,  
});

const salesSchema = new mongoose.Schema({
  username: { type: String },
  phone: { type: String, unique: true, trim: true },
  salesId: { type: String, default: null },
  phoneVerified: { type: Boolean, default: false },
  phoneVerificationCode: { type: Number, default: 11111 },
  passwordResetCode: { type: Number, default: 11111 },
  oneTimePasswordSetFlag: { type: Boolean, default: false },
  emails: {type: String},
  services: {
    password: {
      bcrypt: { type: String, required: true }
    }
  },
  description: { type: String, default: null },
  designation: { type: String, default: null },
  reportingManager: { type: String, default: null },
  departmentName: { type: String, default: null },
  zone: { type: String, default: null },
  profile: {
    role: [{ type: String, default: "sales" }],
    firstName: { type: String, default: null },
    lastName: { type: String, default: null },
    contactNumber: { type: String, default: null },
    alternativeContactNumber: { 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 },
  },
  status: {
    type: String,
    enum: ['inactive', 'active'],
    default: 'active'
  },
  longitude: { type: Number, default: 0.0 },
  latitude: { type: Number, default: 0.0 },
  isActive: Boolean,
  tenantId: ObjectId,
  fcmId: { type: String, default: null },
  createdAt: {
    type: Date,
    default: function () {
      return Date.now();
    },
  },
  createdBy: ObjectId,
  updatedAt: {
    type: Date,
    default: function () {
      return Date.now();
    },
  },
  updatedBy: ObjectId,
}, { versionKey: false });


const masterSlaveDataSchema = new mongoose.Schema({
  installationId: {type: String},
  type: { type: String},
  hardwareId: { type: String },
  batchno: { type: String, default: null },
  masterId: { type: String },
  tankName: { type: String },
  tankLocation: { type: String },
  materialRecived: { type: String },
  electicityWork: { type: String },
  plumbingWork: { type: String },
  loraCheck: { type: String },
 
}, {
  timestamps: true,  
});

const Iotprice = mongoose.model('Iotprice', iotpriceSchema);
  const Insensors = mongoose.model('Insensors', insensorsSchema);
  const MasterSlaveData = mongoose.model('MasterSlaveData', masterSlaveDataSchema);

  
  const Order = mongoose.model('Order', orderSchema);
  const EstimationOrder = mongoose.model('EstimationOrder', estimationorderSchema);

  const Store = mongoose.model("Store", storeSchema);
  const WaterLeverSensor = mongoose.model('WaterLeverSensor', waterLeverSensorInSchema);
  const ProfilePictureStore = mongoose.model('ProfilePictureStore', profilePictureStoreSchema);
  const ProfilePictureInstall = mongoose.model('ProfilePictureInstall', profilePictureInstallSchema);
  const MotorSwitchSensor = mongoose.model('MotorSwitchSensor', motorSwitchSensorInSchema);
  const SensorQuotation = mongoose.model('SensorQuotationSchema', sensorquotationSchema);
  
  const SensorStock = mongoose.model("SensorStock", SensorStockSchema);
  const Install = mongoose.model("Install", installationschema);
  const Survey = mongoose.model("Survey", surveyschema);

  const HardwareCart = mongoose.model("HardwareCart", hardwareCartSchema);
  const ServiceCart = mongoose.model("ServiceCart", serviceCartSchema);
  const Sales = mongoose.model("Sales", salesSchema);

  

  module.exports = {MasterSlaveData,SensorStock,Order,EstimationOrder,Iotprice,Sales, Install,Survey, ProfilePictureInstall, SensorQuotation,generateinstallationId,Store,ProfilePictureStore,WaterLeverSensor,MotorSwitchSensor,Insensors,generatequatationId, HardwareCart, ServiceCart};
