import { Schema, model } from 'mongoose';
import { ITeamDoc, ITeamModel } from '@/modules/teams/teams.interface.js';
import { paginate, toJSON } from '@/shared/utils/plugins/index.js';

const teamSchema = new Schema<ITeamDoc>(
  {
    name: { type: String, required: true },
    description: { type: String },
    members: [{ type: Schema.Types.ObjectId, ref: 'User' }],
    lead: { type: Schema.Types.ObjectId, ref: 'User' },
    createdBy: { type: Schema.Types.ObjectId, ref: 'User' },
    updatedBy: { type: Schema.Types.ObjectId, ref: 'User' },
    companyId: { type: Schema.Types.ObjectId, required: true, ref: 'Company' },
  },
  {
    timestamps: true,
  },
);

teamSchema.index({ name: 1, companyId: 1 }, { unique: true });

// add plugin that converts mongoose to json
teamSchema.plugin(toJSON);
teamSchema.plugin(paginate);

export const Team = model<ITeamDoc, ITeamModel>('Team', teamSchema);
