import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument, Types } from 'mongoose';
import { User } from '../../users/schemas/user.schema';

export type SupportTicketDocument = HydratedDocument<SupportTicket>;

export const SUPPORT_TICKET_CATEGORIES = [
  'account',
  'technical',
  'media',
  'payment',
  'collaboration',
  'other',
] as const;
export type SupportTicketCategory = (typeof SUPPORT_TICKET_CATEGORIES)[number];

export const SUPPORT_TICKET_PRIORITIES = ['low', 'normal', 'high', 'urgent'] as const;
export type SupportTicketPriority = (typeof SUPPORT_TICKET_PRIORITIES)[number];

export const SUPPORT_TICKET_STATUSES = [
  'open',
  'pending',
  'in_progress',
  'resolved',
  'closed',
] as const;
export type SupportTicketStatus = (typeof SUPPORT_TICKET_STATUSES)[number];

@Schema({ timestamps: true, versionKey: false })
export class SupportTicket {
  @Prop({ type: Types.ObjectId, ref: User.name, required: true, index: true })
  userId!: Types.ObjectId;

  @Prop({ type: Types.ObjectId, ref: User.name, default: null, index: true })
  assignedAdminId!: Types.ObjectId | null;

  @Prop({ type: String, required: true, trim: true, maxlength: 150 })
  subject!: string;

  @Prop({ type: String, enum: SUPPORT_TICKET_CATEGORIES, default: 'technical', index: true })
  category!: SupportTicketCategory;

  @Prop({ type: String, enum: SUPPORT_TICKET_PRIORITIES, default: 'normal', index: true })
  priority!: SupportTicketPriority;

  @Prop({ type: String, enum: SUPPORT_TICKET_STATUSES, default: 'open', index: true })
  status!: SupportTicketStatus;

  @Prop({ type: Date, default: Date.now, index: true })
  lastMessageAt!: Date;

  @Prop({ type: Date, default: null })
  resolvedAt!: Date | null;

  @Prop({ type: Date, default: null })
  closedAt!: Date | null;
}

export const SupportTicketSchema = SchemaFactory.createForClass(SupportTicket);
SupportTicketSchema.index({ userId: 1, createdAt: -1 });
SupportTicketSchema.index({ status: 1, updatedAt: -1 });
SupportTicketSchema.index({ category: 1, createdAt: -1 });
SupportTicketSchema.index({ priority: 1, createdAt: -1 });
SupportTicketSchema.index({ assignedAdminId: 1, status: 1 });
SupportTicketSchema.index({ lastMessageAt: -1 });
