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

export type RotationTransactionDocument = RotationTransaction & Document;

export interface RotationOutLine {
  itemId: Types.ObjectId;
  batchId: Types.ObjectId;
  batchNumber: string;
  quantityMt: number;
}

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

/**
 * One document per rotation event: one or more Rotation In items (created
 * into `warehouseId`) paired with one or more Rotation Out items whose
 * quantities sum to the same total MT. Balance-neutral on the global total
 * by construction (+in / -out cancel), but real per-batch InventoryBalance
 * changes happen on approval.
 */
@Schema({ collection: "rotation_transactions", timestamps: false })
export class RotationTransaction {
  @Prop({ type: Types.ObjectId, ref: "Warehouse", required: true })
  declare warehouseId: Types.ObjectId;

  // Vendor — one per transaction, covers the whole rotation (in and out).
  @Prop({ type: Types.ObjectId, ref: "Vendor", required: true })
  declare vendorId: Types.ObjectId;
  @Prop({ required: true })
  declare vendor: string;

  // Voucher — one per transaction, mirrors the GRN sheet-level voucher.
  @Prop({ required: true })
  declare voucher: string;

  // Rotation In — one or more items, all landing in `warehouseId`
  @Prop({ type: [Object], required: true })
  declare rotationIn: RotationInLine[];

  // Rotation Out — one or more items, any item(s), must sum to rotationIn total
  @Prop({ type: [Object], required: true })
  declare rotationOut: RotationOutLine[];

  @Prop({ required: true })
  declare totalMt: 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 RotationTransactionSchema = SchemaFactory.createForClass(RotationTransaction);
RotationTransactionSchema.index({ approvalStatus: 1 });
