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

export type TransferTransactionDocument = TransferTransaction & Document;

export interface TransferLine {
  itemId: Types.ObjectId;
  sourceBatchId: Types.ObjectId;
  sourceWarehouseId: Types.ObjectId;
  batchNumber: string;
  // Destination batch number — defaults to the source's `batchNumber` (the
  // common case: a transfer relocates a batch unchanged). Set this when the
  // stock is repackaged/relabeled under a new batch number at the
  // destination warehouse, so multiple source batches can consolidate into
  // one destination batch (or vice versa) instead of forcing the source's
  // number to carry over.
  destinationBatchNumber: string | null;
  expiryDate: string | null;
  productionDate: string | null;
  quantityMt: number;
}

/**
 * One document per transfer event: one or more lines, each relocating
 * existing stock of one item/batch from its source warehouse into
 * `destinationWarehouseId`, under `destinationBatchNumber` (defaults to the
 * source's own batch number when not relabeled). Net zero on the global
 * total by construction (the same quantity leaves one warehouse and lands
 * in another) — real per-batch InventoryBalance changes happen on approval,
 * same pattern as RotationTransaction.
 */
@Schema({ collection: "transfer_transactions", timestamps: false })
export class TransferTransaction {
  @Prop({ type: Types.ObjectId, ref: "Warehouse", required: true })
  declare destinationWarehouseId: Types.ObjectId;

  // Vendor — optional, one per transaction. A transfer relocates stock the
  // company already owns, so unlike GRN/Rotation-In there's no goods
  // origin to require, but it's captured here too when relevant.
  @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], required: true })
  declare lines: TransferLine[];

  @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 TransferTransactionSchema = SchemaFactory.createForClass(TransferTransaction);
TransferTransactionSchema.index({ approvalStatus: 1 });
