/**
 * Support Team Model
 *
 * Super-admin-managed support teams for the Ticket Support system. Tickets can
 * be assigned to a team; members of that team may then view and manage the
 * tickets assigned to it. Members are stored as lightweight snapshots
 * (userId + name + email) so team lists render without user joins — matching
 * the denormalised style used elsewhere (e.g. createdByName on tickets).
 */

import mongoose, { Schema, Document } from 'mongoose';

export interface ISupportTeamMember {
  userId: string;
  name: string;
  email?: string;
}

export interface ISupportTeam extends Document {
  name: string;
  description?: string;
  members: ISupportTeamMember[];
  createdByName?: string;
  createdAt: Date;
  updatedAt: Date;
}

const MemberSchema = new Schema<ISupportTeamMember>(
  {
    userId: { type: String, required: true },
    name: { type: String, required: true },
    email: { type: String },
  },
  { _id: false },
);

const SupportTeamSchema = new Schema<ISupportTeam>(
  {
    name: {
      type: String,
      required: [true, 'Team name is required'],
      trim: true,
      maxlength: [100, 'Team name cannot exceed 100 characters'],
    },
    description: { type: String, trim: true, maxlength: [500, 'Description cannot exceed 500 characters'], default: '' },
    members: { type: [MemberSchema], default: [] },
    createdByName: { type: String },
  },
  { timestamps: true },
);

// Member-of lookups ("which teams is this user in?") and name sorting.
SupportTeamSchema.index({ 'members.userId': 1 });
SupportTeamSchema.index({ name: 1 });

export const SupportTeam =
  mongoose.models.SupportTeam || mongoose.model<ISupportTeam>('SupportTeam', SupportTeamSchema);
