// models/customerPayment.ts
import { Schema, model } from 'mongoose';
import { paginate, toJSON } from '@/shared/utils/plugins';
import { PaymentMethod, PaymentStatus } from './payment.helper';

const PaymentEntrySchema = new Schema(
  {
    amount: { type: Number, required: true, min: 0 },
    receivedAt: { type: Date, default: new Date() },
    bankAccountId: { type: Schema.Types.ObjectId, ref: 'BankAccount' },
    method: {
      type: String,
      enum: Object.values(PaymentMethod),
      default: PaymentMethod.CASH,
    },
    note: { type: String, trim: true },
  },
  { _id: true },
);

const StageSchema = new Schema(
  {
    label: { type: String, required: true, trim: true },
    dueDate: { type: Date },
    dueAmount: { type: Number, min: 0 },
    paid: { type: Number, default: 0, min: 0 },
    lastPaidAt: { type: Date },
    bankAccountId: { type: Schema.Types.ObjectId, ref: 'BankAccount' },
    payments: { type: [PaymentEntrySchema], default: [] },
    status: {
      type: String,
      enum: Object.values(PaymentStatus),
      default: PaymentStatus.PENDING,
      index: true,
    },
    method: {
      type: String,
      enum: Object.values(PaymentMethod),
      default: PaymentMethod.CASH,
    },
  },
  { _id: true },
);

export const CustomerPaymentSchema = new Schema(
  {
    company: { type: Schema.Types.ObjectId, ref: 'Company', index: true },
    customerId: {
      type: Schema.Types.ObjectId,
      ref: 'Customer',
      index: true,
    },

    totalAmount: { type: Number, default: 0, min: 0 }, // sum of dueAmount
    paidAmount: { type: Number, default: 0, min: 0 }, // sum of all stage.paid
    overallStatus: {
      type: String,
      enum: ['pending', 'partial', 'paid', 'overdue'],
      default: 'pending',
      index: true,
    },

    timeline: { type: [StageSchema], default: [] },

    createdBy: { type: Schema.Types.ObjectId, ref: 'User' },
    updatedBy: { type: Schema.Types.ObjectId, ref: 'User' },
  },
  { timestamps: true },
);

// plugins
CustomerPaymentSchema.plugin(toJSON);
CustomerPaymentSchema.plugin(paginate);

// indexes helpful for reminders and lists
CustomerPaymentSchema.index({ 'timeline.dueDate': 1 });
CustomerPaymentSchema.index({ customerId: 1, projectId: 1 });

export const CustomerPayment = model('CustomerPayment', CustomerPaymentSchema);
