/**
 * Invoice Model
 * Auto-generated after payment, tracks billing history per company.
 */

import mongoose, { Schema, Document } from 'mongoose';

export type InvoiceStatus = 'paid' | 'pending' | 'failed' | 'refunded';

export interface IInvoice extends Document {
  companyId: string;
  subscriptionId: string;
  invoiceNumber: string;
  packageName: string;
  billingCycle: string;
  amount: number;
  currency: string;
  taxAmount?: number;
  taxRate?: number;
  totalAmount: number;
  paymentGateway: string;
  transactionId?: string;
  status: InvoiceStatus;
  paidAt?: Date;
  pdfUrl?: string;
  // Dynamic pricing engine fields
  pricingBreakdown?: {
    items: { slug: string; name: string; unitPrice: number; quantity: number; subtotal: number }[];
    addons: { slug: string; name: string; unitPrice: number; quantity: number; subtotal: number }[];
    discounts: { code: string; name: string; amount: number }[];
    taxes: { name: string; rate: number; amount: number }[];
    subtotal: number;
    total: number;
  };
  createdAt: Date;
  updatedAt: Date;
}

const InvoiceSchema = new Schema<IInvoice>({
  companyId: {
    type: String,
    required: [true, 'Company ID is required'],
    index: true,
  },
  subscriptionId: {
    type: String,
    required: [true, 'Subscription ID is required'],
  },
  invoiceNumber: {
    type: String,
    required: [true, 'Invoice number is required'],
    unique: true,
    trim: true,
  },
  packageName: {
    type: String,
    required: [true, 'Package name is required'],
    trim: true,
  },
  billingCycle: {
    type: String,
    enum: ['monthly', 'quarterly', 'half_yearly', 'yearly', 'lifetime'],
    required: [true, 'Billing cycle is required'],
  },
  amount: {
    type: Number,
    required: [true, 'Amount is required'],
    min: [0, 'Amount cannot be negative'],
  },
  currency: {
    type: String,
    enum: ['USD', 'INR', 'AED'],
    default: 'USD',
  },
  taxAmount: {
    type: Number,
    min: [0, 'Tax amount cannot be negative'],
  },
  taxRate: {
    type: Number,
    min: [0, 'Tax rate cannot be negative'],
  },
  totalAmount: {
    type: Number,
    required: [true, 'Total amount is required'],
    min: [0, 'Total amount cannot be negative'],
  },
  paymentGateway: {
    type: String,
    enum: ['stripe', 'razorpay', 'manual'],
    default: 'manual',
  },
  transactionId: {
    type: String,
    sparse: true,
  },
  status: {
    type: String,
    enum: ['paid', 'pending', 'failed', 'refunded'],
    default: 'pending',
  },
  paidAt: {
    type: Date,
  },
  pdfUrl: {
    type: String,
    trim: true,
  },
  pricingBreakdown: {
    type: Schema.Types.Mixed,
    default: null,
  },
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true },
});

InvoiceSchema.index({ companyId: 1, createdAt: -1 });
InvoiceSchema.index({ subscriptionId: 1 });
InvoiceSchema.index({ invoiceNumber: 1 }, { unique: true });
InvoiceSchema.index({ status: 1 });

export const Invoice = mongoose.models.Invoice || mongoose.model<IInvoice>('Invoice', InvoiceSchema);