import mongoose from 'mongoose';
import { HouseholdRole } from '@meshitrack/shared';

const householdMemberSchema = new mongoose.Schema(
  {
    userId: { type: String, required: true },
    role: { type: String, enum: Object.values(HouseholdRole), required: true },
    joinedAt: { type: Date, default: Date.now },
  },
  { _id: false },
);

const householdSettingsSchema = new mongoose.Schema(
  {
    timezone: { type: String, default: 'UTC' },
    currency: { type: String, default: 'USD', maxlength: 3 },
    language: { type: String, default: 'en', maxlength: 5 },
  },
  { _id: false },
);

const householdSchema = new mongoose.Schema(
  {
    name: { type: String, required: true },
    ownerUserId: { type: String, required: true, index: true },
    members: { type: [householdMemberSchema], default: [] },
    inviteCode: { type: String, required: true, index: true },
    /* v8 ignore start -- Mongoose default factory, only invoked at document creation */
    settings: {
      type: householdSettingsSchema,
      default: () => ({ timezone: 'UTC', currency: 'USD', language: 'en' }),
    },
    /* v8 ignore stop */
  },
  {
    timestamps: true,
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  },
);

export const HouseholdModel = mongoose.model('Household', householdSchema);
export type HouseholdDocument = mongoose.InferSchemaType<typeof householdSchema> & {
  _id: mongoose.Types.ObjectId;
};
