const mongoose = require("mongoose");

const branchSchema = new mongoose.Schema(
  {
    branchId: {
      type: String,
      required: true,
      unique: true,
      trim: true,
      uppercase: true,
    },

    branchCode: {
      type: String,
      // trim: true,
      uppercase: true,
    },

    branchName: {
      type: String,
      required: true,
      trim: true,
      minlength: 3,
      maxlength: 100,
    },

    branchType: {
      type: String,
      enum: ["Urban", "Semi-Urban", "Rural"],
      default: "Urban",
    },

    openingDate: {
      type: Date,
    },

    manager: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },

    parentBranchId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Branch",
      default: null,
    },
    address: {
      street: String,
      area: String,
      city: {
        type: String,
        required: true,
      },
      state: {
        type: String,
        required: true,
      },
      country: {
        type: String,
        default: "India",
      },
      postalCode: String,
      geoLocation: {
        latitude: Number,
        longitude: Number,
      },
    },
    contact: {
      phone: {
        type: String,
        required: true,
        match: [/^[0-9]{10}$/, "Phone must be 10 digits"],
      },
      email: {
        type: String,
        lowercase: true,
        trim: true,
      },
      fax: String,
      website: String,
    },
    operationalHours: {
      monday: String,
      tuesday: String,
      wednesday: String,
      thursday: String,
      friday: String,
      saturday: String,
      sunday: String,
    },
    ifscCode: {
      type: String,
      trim: true,
      uppercase: true,
    },

    swiftCode: {
      type: String,
      trim: true,
      uppercase: true,
    },
    services: [
      {
        type: String,
        trim: true,
      },
    ],

    facilities: {
      atmAvailable: Boolean,
      wheelchairAccess: Boolean,
      parking: Boolean,
      lockerFacility: Boolean,
    },
    compliance: {
      lastAuditDate: Date,
      auditStatus: {
        type: String,
        enum: ["Compliant", "Non-Compliant"],
      },
      licenseValidTill: Date,
    },
    emergencyContacts: {
      fireSafetyOfficer: String,
      policeStation: String,
    },
    notes: {
      type: String,
      maxlength: 500,
    },
    status: {
      type: String,
      enum: ["Active", "Inactive"],
      default: "Active",
    },

    orgId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Organization",
      required: true,
    },
    createdBy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },

    updatedBy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },

    isDeleted: {
      type: Boolean,
      default: false,
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model("Branch", branchSchema);
