import { paginate, toJSON } from '@/shared/utils/plugins';
import { model, Schema } from 'mongoose';
import { IUnitDoc, IUnitModel } from '../project.interface';

const unitSchema = new Schema<IUnitDoc>(
  {
    project: {
      type: Schema.Types.ObjectId,
      ref: 'Project',
      required: true,
    },
    propertyType: {
      type: Schema.Types.ObjectId,
      ref: 'Category',
      required: true,
    },
    unitNumber: {
      type: String,
      required: true,
      default: '',
      trim: true,
    },
    size: {
      type: Number,
      required: true,
    },
    price: {
      type: Number,
      required: true,
    },
    status: {
      type: String,
      enum: ['sold', 'hold', 'available'],
      default: 'available',
    },
    createdBy: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
    updatedBy: {
      type: Schema.Types.ObjectId,
      ref: 'User',
    },
    block: {
      type: String,
      trim: true,
      default: null,
    },
    floor: {
      type: Number,
      default: null,
    },
    customFields: {
      type: Map,
      of: Schema.Types.Mixed,
      default: {},
    },
  },
  {
    timestamps: true,
  },
);

unitSchema.index({ project: 1, block: 1, unitNumber: 1 }, { unique: true });

unitSchema.plugin(toJSON);
unitSchema.plugin(paginate);

const Unit = model<IUnitDoc, IUnitModel>('Unit', unitSchema);

export default Unit;
