import { Schema, model } from 'mongoose'

import { IState, IStateModel } from '@/modules/master/location/location.interfaces.js'
import { paginate, toJSON } from '@/shared/utils/plugins/index.js'

const stateSchema = new Schema<IState>(
  {
    name: { type: String, trim: true, unique: true },
    country: { type: Schema.Types.ObjectId, ref: 'Country' },
    loc: {
      type: {
        type: String,
        enum: ['Point'],
        required: true,
      },
      coordinates: {
        type: [Number],
        required: true,
      },
    },
    createdBy: { type: Schema.Types.ObjectId, ref: 'User' },
    updatedBy: { type: Schema.Types.ObjectId, ref: 'User' },
  },
  { timestamps: true },
)

// Add plugins
stateSchema.plugin(toJSON)
stateSchema.plugin(paginate)

// Add 2dsphere index on loc with uniqueness
// stateSchema.index({ loc: '2dsphere' }, { unique: true })

const State = model<IState, IStateModel>('State', stateSchema)
export default State
