import mongoose, { Schema, Document, Model } from 'mongoose';

export interface ICountry extends Document {
  name: string;
  code: string;
  isActive: boolean;
}

export interface IState extends Document {
  name: string;
  countryId: mongoose.Types.ObjectId;
  isActive: boolean;
}

export interface ICity extends Document {
  name: string;
  stateId: mongoose.Types.ObjectId;
  countryId: mongoose.Types.ObjectId;
  isActive: boolean;
}

export interface IArea extends Document {
  name: string;
  cityId: mongoose.Types.ObjectId;
  isActive: boolean;
}

const CountrySchema = new Schema<ICountry>({
  name: { type: String, required: true, trim: true },
  code: { type: String, required: true, trim: true },
  isActive: { type: Boolean, default: true },
});

const StateSchema = new Schema<IState>({
  name: { type: String, required: true, trim: true },
  countryId: { type: Schema.Types.ObjectId, ref: 'Country', required: true },
  isActive: { type: Boolean, default: true },
});

const CitySchema = new Schema<ICity>({
  name: { type: String, required: true, trim: true },
  stateId: { type: Schema.Types.ObjectId, ref: 'State', required: true },
  countryId: { type: Schema.Types.ObjectId, ref: 'Country', required: true },
  isActive: { type: Boolean, default: true },
});

const AreaSchema = new Schema<IArea>({
  name: { type: String, required: true, trim: true },
  cityId: { type: Schema.Types.ObjectId, ref: 'City', required: true },
  isActive: { type: Boolean, default: true },
});

// Avoid OverwriteModelError during Next.js hot reloads
export const Country: Model<ICountry> = mongoose.models.Country || mongoose.model<ICountry>('Country', CountrySchema);
export const State: Model<IState> = mongoose.models.State || mongoose.model<IState>('State', StateSchema);
export const City: Model<ICity> = mongoose.models.City || mongoose.model<ICity>('City', CitySchema);
export const Area: Model<IArea> = mongoose.models.Area || mongoose.model<IArea>('Area', AreaSchema);
