const mongoose = require('mongoose');

const slaTrackerSchema = new mongoose.Schema({
  companyId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Company',
    required: true
  },
  slaId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'SLA',
    required: true
  },
  entityType: {
    type: String,
    enum: ['Lead', 'Proposal', 'Ticket', 'Task'],
    required: true
  },
  entityId: {
    type: mongoose.Schema.Types.ObjectId,
    required: true
  },
  priority: {
    type: String,
    enum: ['low', 'medium', 'high', 'urgent', 'critical'],
    required: true
  },
  status: {
    type: String,
    enum: ['pending', 'in_progress', 'paused', 'met', 'breached', 'cancelled'],
    default: 'pending'
  },
  response: {
    targetTime: Date,
    actualTime: Date,
    status: {
      type: String,
      enum: ['pending', 'met', 'breached', 'warning'],
      default: 'pending'
    },
    breachTime: Number, // Minutes breached
    metBy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    }
  },
  resolution: {
    targetTime: Date,
    actualTime: Date,
    status: {
      type: String,
      enum: ['pending', 'met', 'breached', 'warning'],
      default: 'pending'
    },
    breachTime: Number,
    resolvedBy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    }
  },
  timeline: {
    startTime: {
      type: Date,
      required: true,
      default: Date.now
    },
    pausedAt: Date,
    resumedAt: Date,
    totalPausedTime: {
      type: Number,
      default: 0 // Minutes
    },
    completedAt: Date
  },
  escalations: [{
    level: Number,
    triggeredAt: Date,
    escalatedTo: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    },
    reason: String,
    resolved: {
      type: Boolean,
      default: false
    },
    resolvedAt: Date
  }],
  notifications: [{
    type: {
      type: String,
      enum: ['warning', 'breach', 'escalation']
    },
    sentAt: Date,
    sentTo: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    }],
    message: String
  }],
  metrics: {
    responseTimeMinutes: Number,
    resolutionTimeMinutes: Number,
    businessHoursUsed: Number,
    breachCount: {
      type: Number,
      default: 0
    }
  }
}, {
  timestamps: true
});

// Indexes
slaTrackerSchema.index({ companyId: 1, status: 1 });
slaTrackerSchema.index({ slaId: 1 });
slaTrackerSchema.index({ entityType: 1, entityId: 1 });
slaTrackerSchema.index({ 'response.status': 1 });
slaTrackerSchema.index({ 'resolution.status': 1 });
slaTrackerSchema.index({ 'response.targetTime': 1 });
slaTrackerSchema.index({ 'resolution.targetTime': 1 });

module.exports = mongoose.model('SLATracker', slaTrackerSchema);