const mongoose = require('mongoose');
const { tenantFields, moneySchema, applyPlatformPlugins } = require('../platformFields');

const itemSchema = new mongoose.Schema({
  product: { type: mongoose.Schema.ObjectId, ref: 'Product', autopopulate: true },
  name: String,
  sku: String,
  quantity: { type: Number, default: 1 },
  unitPrice: moneySchema,
  total: moneySchema,
}, { _id: false });

const paymentSchema = new mongoose.Schema({
  mode: String,
  amount: moneySchema,
  reference: String,
}, { _id: false });

const schema = new mongoose.Schema({
  ...tenantFields,
  session: { type: mongoose.Schema.ObjectId, ref: 'PosSession', autopopulate: true },
  branch: { type: mongoose.Schema.ObjectId, ref: 'Branch', required: true, autopopulate: true },
  cashier: { type: mongoose.Schema.ObjectId, ref: 'Admin', required: true, autopopulate: true },
  customer: { type: mongoose.Schema.ObjectId, ref: 'Client', autopopulate: true },
  invoice: { type: mongoose.Schema.ObjectId, ref: 'Invoice', autopopulate: true },
  payment: { type: mongoose.Schema.ObjectId, ref: 'Payment', autopopulate: true },
  receiptNumber: { type: String, required: true },
  items: [itemSchema],
  subtotal: moneySchema,
  total: moneySchema,
  paymentSummary: paymentSchema,
  notes: String,
  soldAt: { type: Date, default: Date.now },
});

module.exports = mongoose.model('PosSale', applyPlatformPlugins(schema));
