import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { Document, Types } from "mongoose";

export type StockAdjustmentDocument = StockAdjustment & Document;

export interface AdjustmentLine {
  warehouseId: Types.ObjectId;
  itemId: Types.ObjectId;
  batchId: Types.ObjectId;
  batchNumber: string;
  expiryDate: string | null;
  productionDate: string | null;
  quantityMt: number;
}

/**
 * One document per correction event: one or more Adjustment In lines and/or
 * one or more Adjustment Out lines. Unlike RotationTransaction, In and Out
 * are independent corrections (not the same stock moving) — they are NOT
 * required to sum to the same total, and each line carries its own
 * `warehouseId` rather than sharing one destination for the whole document.
 * Real per-batch InventoryBalance changes happen on approval, same as
 * RotationTransaction.
 */
@Schema({ collection: "stock_adjustments", timestamps: false })
export class StockAdjustment {
  // Voucher — optional; a one-off manual correction may not have one.
  @Prop({ type: String, default: null })
  declare voucher: string | null;

  // Vendor — optional, one per transaction (corrections often have none).
  @Prop({ type: Types.ObjectId, ref: "Vendor", default: null })
  declare vendorId: Types.ObjectId | null;
  @Prop({ type: String, default: null })
  declare vendor: string | null;

  @Prop({ type: [Object], default: [] })
  declare adjustmentIn: AdjustmentLine[];

  @Prop({ type: [Object], default: [] })
  declare adjustmentOut: AdjustmentLine[];

  @Prop({ required: true, default: 0 })
  declare totalInMt: number;

  @Prop({ required: true, default: 0 })
  declare totalOutMt: number;

  @Prop({
    required: true,
    enum: ["pending_approval", "approved", "rejected"],
    default: "pending_approval",
  })
  declare approvalStatus: string;

  @Prop({ type: String, default: null }) declare approvedBy: string | null;
  @Prop({ type: String, default: null }) declare approvedAt: string | null;
  @Prop({ type: String, default: null }) declare rejectedBy: string | null;
  @Prop({ type: String, default: null }) declare rejectedAt: string | null;
  @Prop({ type: String, default: null }) declare rejectedReason: string | null;
  @Prop({ type: String, default: null }) declare submittedBy: string | null;

  @Prop({ required: true })
  declare createdAt: string;
}

export const StockAdjustmentSchema = SchemaFactory.createForClass(StockAdjustment);
StockAdjustmentSchema.index({ approvalStatus: 1 });
