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

export type SupportTicketMessageDocument = HydratedDocument<SupportTicketMessage>;

export const SUPPORT_MESSAGE_SENDER_ROLES = ['user', 'admin', 'superadmin', 'system'] as const;
export type SupportMessageSenderRole = (typeof SUPPORT_MESSAGE_SENDER_ROLES)[number];

export const SUPPORT_MESSAGE_ATTACHMENT_TYPES = ['image', 'file'] as const;
export type SupportMessageAttachmentType = (typeof SUPPORT_MESSAGE_ATTACHMENT_TYPES)[number];

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

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

  @Prop({ type: String, default: '', trim: true, index: true })
  senderIdentifier!: string;

  @Prop({ type: String, enum: SUPPORT_MESSAGE_SENDER_ROLES, required: true })
  senderRole!: SupportMessageSenderRole;

  @Prop({ type: String, default: '', trim: true, maxlength: 5000 })
  message!: string;

  @Prop({ type: String, default: '', trim: true })
  attachmentUrl!: string;

  @Prop({ type: String, enum: SUPPORT_MESSAGE_ATTACHMENT_TYPES, default: null })
  attachmentType!: SupportMessageAttachmentType | null;

  @Prop({ type: Boolean, default: false })
  readByUser!: boolean;

  @Prop({ type: Boolean, default: false })
  readByAdmin!: boolean;
}

export const SupportTicketMessageSchema = SchemaFactory.createForClass(SupportTicketMessage);
SupportTicketMessageSchema.index({ ticketId: 1, createdAt: 1 });
SupportTicketMessageSchema.index({ senderId: 1, createdAt: -1 });
