import mongoose, { Schema, Document } from 'mongoose';

export interface ITicketDocument extends Document {
  _id: any;
  ticketCode: string;
  projectId: any;
  assetId: any;
  title: string;
  description?: string;
  status: 'Open' | 'InProgress' | 'Resolved' | 'Closed';
  priority: 'Low' | 'Medium' | 'High' | 'Critical';
  reportedBy: any;
  assignedTo?: any;
  category: 'Electrical' | 'Mechanical' | 'Inverter' | 'Solar Panel' | 'Communication' | 'Other';
  images?: string[];
  slaDeadline?: Date;
  createdAt: Date;
  updatedAt: Date;
}

const ticketSchema = new Schema<ITicketDocument>(
  {
    _id: { type: Schema.Types.Mixed, default: () => new mongoose.Types.ObjectId().toString() }, // Support both string demo IDs and auto-gen string IDs
    ticketCode: { type: String, required: true, unique: true },
    projectId: { type: Schema.Types.Mixed, ref: 'Project', required: true },
    assetId: { type: Schema.Types.Mixed, ref: 'Asset', required: true },
    title: { type: String, required: true },
    description: String,
    status: {
      type: String,
      enum: ['Open', 'InProgress', 'Resolved', 'Closed'],
      default: 'Open',
    },
    priority: {
      type: String,
      enum: ['Low', 'Medium', 'High', 'Critical'],
      default: 'Medium',
    },
    reportedBy: { type: Schema.Types.Mixed, ref: 'User', required: true },
    assignedTo: { type: Schema.Types.Mixed },
    category: {
      type: String,
      enum: ['Electrical', 'Mechanical', 'Inverter', 'Solar Panel', 'Communication', 'Other'],
      default: 'Other',
    },
    images: [String],
    slaDeadline: Date,
  },
  {
    timestamps: true,
    strict: false,
  }
);

ticketSchema.index({ projectId: 1 });
ticketSchema.index({ assetId: 1 });
ticketSchema.index({ status: 1 });
ticketSchema.index({ priority: 1 });
ticketSchema.index({ reportedBy: 1 });
ticketSchema.index({ assignedTo: 1 });
ticketSchema.index({ createdAt: -1 });

export const Ticket = mongoose.model<ITicketDocument>('Ticket', ticketSchema);
