import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument } from 'mongoose';

export type SuperAdminCaseDocument = HydratedDocument<SuperAdminCase>;

export const SUPERADMIN_CASE_STATUSES = ['open', 'in_review', 'resolved'] as const;
export const SUPERADMIN_CASE_PRIORITIES = ['low', 'normal', 'high', 'critical'] as const;
export type SuperAdminCaseStatus = (typeof SUPERADMIN_CASE_STATUSES)[number];
export type SuperAdminCasePriority = (typeof SUPERADMIN_CASE_PRIORITIES)[number];

@Schema({ timestamps: true, versionKey: false })
export class SuperAdminCase {
  @Prop({ required: true, trim: true, maxlength: 120, index: true })
  title!: string;

  @Prop({ default: '', trim: true, maxlength: 2000 })
  description!: string;

  @Prop({ required: true, trim: true, index: true })
  caseType!: string;

  @Prop({ required: true, trim: true, index: true })
  resourceType!: string;

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

  @Prop({
    required: true,
    enum: SUPERADMIN_CASE_STATUSES,
    default: 'open',
    index: true,
  })
  status!: SuperAdminCaseStatus;

  @Prop({
    required: true,
    enum: SUPERADMIN_CASE_PRIORITIES,
    default: 'normal',
    index: true,
  })
  priority!: SuperAdminCasePriority;

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

  @Prop({ default: '', trim: true })
  createdBy!: string;

  @Prop({ default: '', trim: true })
  updatedBy!: string;

  @Prop({ type: [String], default: [] })
  tags!: string[];

  @Prop({ default: '', trim: true, maxlength: 1200 })
  resolution!: string;

  @Prop({
    type: [
      {
        action: { type: String, required: true, trim: true },
        actor: { type: String, required: true, trim: true },
        note: { type: String, default: '', trim: true, maxlength: 1200 },
        metadata: { type: Object, default: {} },
        createdAt: { type: Date, default: Date.now },
      },
    ],
    default: [],
  })
  events!: Array<{
    action: string;
    actor: string;
    note: string;
    metadata?: Record<string, unknown>;
    createdAt: Date;
  }>;
}

export const SuperAdminCaseSchema = SchemaFactory.createForClass(SuperAdminCase);

SuperAdminCaseSchema.index({ status: 1, priority: 1, updatedAt: -1 });
SuperAdminCaseSchema.index({ resourceType: 1, resourceId: 1, updatedAt: -1 });
