const mongoose = require('mongoose');

const proposalItemSchema = new mongoose.Schema({
  productId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Product'
  },
  description: {
    type: String,
    required: true
  },
  quantity: {
    type: Number,
    required: true,
    min: 1
  },
  unitPrice: {
    type: Number,
    required: true,
    min: 0
  },
  discount: {
    type: Number,
    default: 0,
    min: 0,
    max: 100
  },
  taxRate: {
    type: Number,
    default: 0
  },
  total: {
    type: Number,
    required: true
  }
}, { _id: true });

const proposalSchema = new mongoose.Schema({
  companyId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Company',
    required: true
  },
  leadId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Lead'
  },
  proposalNumber: {
    type: String,
    required: true,
    unique: true
  },
  title: {
    type: String,
    required: [true, 'Proposal title is required'],
    trim: true
  },
  customer: {
    name: {
      type: String,
      required: true
    },
    email: {
      type: String,
      required: true
    },
    phone: String,
    company: String,
    address: {
      street: String,
      city: String,
      state: String,
      pincode: String,
      country: String
    }
  },
  items: [proposalItemSchema],
  pricing: {
    subtotal: {
      type: Number,
      required: true,
      default: 0
    },
    discount: {
      type: Number,
      default: 0
    },
    taxAmount: {
      type: Number,
      default: 0
    },
    total: {
      type: Number,
      required: true,
      default: 0
    },
    currency: {
      type: String,
      default: 'INR'
    }
  },
  terms: {
    validUntil: {
      type: Date,
      required: true
    },
    paymentTerms: {
      type: String,
      default: 'Net 30'
    },
    deliveryTime: String,
    notes: String,
    termsAndConditions: String
  },
  status: {
    type: String,
    enum: ['draft', 'sent', 'viewed', 'accepted', 'rejected', 'expired', 'completed'],
    default: 'draft'
  },
  priority: {
    type: String,
    enum: ['low', 'medium', 'high', 'urgent'],
    default: 'medium'
  },
  workflow: {
    currentStage: {
      type: String,
      enum: ['maker', 'checker', 'verifier', 'completed'],
      default: 'maker'
    },
    maker: {
      userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
      },
      status: {
        type: String,
        enum: ['draft', 'submitted', 'rejected'],
        default: 'draft'
      },
      submittedAt: Date,
      comments: String
    },
    checker: {
      userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
      },
      status: {
        type: String,
        enum: ['pending', 'in_progress', 'sent_back', 'forwarded'],
        default: 'pending'
      },
      reviewedAt: Date,
      comments: String
    },
    verifier: {
      userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
      },
      status: {
        type: String,
        enum: ['pending', 'approved', 'rejected'],
        default: 'pending'
      },
      approvedAt: Date,
      comments: String
    }
  },
  attachments: [{
    name: String,
    url: String,
    size: Number,
    type: String,
    uploadedAt: {
      type: Date,
      default: Date.now
    }
  }],
  sentDate: Date,
  viewedDate: Date,
  acceptedDate: Date,
  rejectedDate: Date,
  rejectionReason: String,
  metadata: {
    version: {
      type: Number,
      default: 1
    },
    revisions: [{
      version: Number,
      revisedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
      },
      revisedAt: Date,
      changes: String
    }]
  },
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  }
}, {
  timestamps: true
});

// Generate proposal number before saving
proposalSchema.pre('save', async function(next) {
  if (!this.isNew) return next();
  
  const Company = mongoose.model('Company');
  const company = await Company.findById(this.companyId);
  const count = await this.constructor.countDocuments({ companyId: this.companyId });
  
  this.proposalNumber = `PROP-${company.code}-${String(count + 1).padStart(5, '0')}`;
  next();
});

// Calculate pricing before saving
proposalSchema.pre('save', function(next) {
  if (this.items && this.items.length > 0) {
    let subtotal = 0;
    let taxAmount = 0;
    
    this.items.forEach(item => {
      const itemSubtotal = item.quantity * item.unitPrice;
      const discountAmount = (itemSubtotal * item.discount) / 100;
      const itemTotal = itemSubtotal - discountAmount;
      const itemTax = (itemTotal * item.taxRate) / 100;
      
      item.total = itemTotal + itemTax;
      subtotal += itemTotal;
      taxAmount += itemTax;
    });
    
    this.pricing.subtotal = subtotal;
    this.pricing.taxAmount = taxAmount;
    this.pricing.total = subtotal + taxAmount - this.pricing.discount;
  }
  next();
});

// Indexes
proposalSchema.index({ companyId: 1, status: 1 });
proposalSchema.index({ proposalNumber: 1 });
proposalSchema.index({ 'customer.email': 1 });
proposalSchema.index({ 'workflow.currentStage': 1 });
proposalSchema.index({ 'workflow.maker.userId': 1 });
proposalSchema.index({ 'workflow.checker.userId': 1 });
proposalSchema.index({ 'workflow.verifier.userId': 1 });

module.exports = mongoose.model('Proposal', proposalSchema);