const mongoose = require('mongoose');

const itemSchema = new mongoose.Schema({
  service: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Service',
    required: true
  },
  quantity: {
    type: Number,
    required: true,
    min: 1
  },
  priceAtTime: { // Snapshot of price when requested
    type: Number,
    required: true
  }
});

const requisitionSchema = new mongoose.Schema({
  company: { type: mongoose.Schema.Types.ObjectId, ref: 'Company', required: true },
  number: { type: String, required: true },
  client: { type: mongoose.Schema.Types.ObjectId, ref: 'Client', required: true },
  origin: { 
    type: String, 
    enum: ['internal', 'external'], 
    default: 'external' 
  },
  items: [itemSchema], // Array of items
  // REMOVED: quantity (redundant for multi-items)
  deliveryDate: { type: Date },
  paymentTerms: { type: String },
  notes: { type: String },
  
  // Installment Logic
  requestedInstallments: { type: Number, default: 1 },
  requestIntent: {
  type: String,
  enum: ['quotation', 'invoice', 'unspecified'],
  default: 'unspecified'
},
  baseTotal: { type: Number, default: 0 }, // Price before installment penalty (now calculated from items)
  finalTotal: { type: Number, default: 0 }, // Price after installment penalty
  
  status: {
    type: String,
    enum: [
      'pending', 
      'approved', 
      'rejected', 
      'quotation_requested',       // ← add
    'invoice_requested',         // ← add
      'converted_to_quotation', // Novo estágio: Cotação
      'converted_to_invoice'
    ],
  default: 'pending'
}
}, { timestamps: true });

// Updated pre-save hook for multi-items
requisitionSchema.pre('save', async function(next) {
  if (this.isNew || this.isModified('items') || this.isModified('requestedInstallments')) {
    const Service = mongoose.model('Service');
    
    if (!this.items || this.items.length === 0) {
      return next(new Error('At least one item is required'));
    }

    // Calculate baseTotal from items (sum priceAtTime * quantity)
    let baseTotal = 0;
    let minAllowedInstallments = Infinity;
    let maxPenaltyRate = 0;

    for (const item of this.items) {
      // Validate/ensure priceAtTime is set (fallback to current service price if missing)
      if (!item.priceAtTime) {
        const serviceData = await Service.findById(item.service);
        if (!serviceData) return next(new Error(`Service ${item.service} not found`));
        item.priceAtTime = serviceData.basePrice;
      }
      
      baseTotal += item.priceAtTime * item.quantity;

      // Fetch service for installment rules (use strictest across all items)
      const serviceData = await Service.findById(item.service);
      if (!serviceData) return next(new Error(`Service ${item.service} not found`));
      
      if (serviceData.allowedInstallments < minAllowedInstallments) {
        minAllowedInstallments = serviceData.allowedInstallments;
      }
      if (serviceData.penaltyPercentagePerInstallment > maxPenaltyRate) {
        maxPenaltyRate = serviceData.penaltyPercentagePerInstallment;
      }
    }

    this.baseTotal = baseTotal;

    // Calculate penalty if installments exceed allowed (using strictest rules)
    if (this.requestedInstallments > minAllowedInstallments) {
      const extraInstallments = this.requestedInstallments - minAllowedInstallments;
      const totalPenaltyPercentage = extraInstallments * maxPenaltyRate;
      this.finalTotal = baseTotal + (baseTotal * (totalPenaltyPercentage / 100));
    } else {
      this.finalTotal = baseTotal;
    }
  }
  
  next();
});

module.exports = mongoose.model('Requisition', requisitionSchema);