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

export type StockTransactionDocument = StockTransaction & Document;

/**
 * Represents a manually entered inbound or outbound stock transaction.
 * Inventory is only updated after a Store_Manager approves the transaction.
 */
@Schema({ collection: "stock_transactions", timestamps: false })
export class StockTransaction {
  @Prop({ required: true, enum: ["inbound", "outbound"] })
  declare type: string;

  @Prop({ type: Types.ObjectId, ref: "Warehouse", required: true })
  declare warehouseId: Types.ObjectId;

  @Prop({ type: Types.ObjectId, ref: "Item", required: true })
  declare itemId: Types.ObjectId;

  @Prop({ type: Types.ObjectId, ref: "Batch", required: true })
  declare batchId: Types.ObjectId;

  @Prop({ required: true })
  declare quantityMt: number;

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

  @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;

  // Optional supplier / invoice fields (populated when invoice is uploaded)
  @Prop({ type: String, default: null }) declare supplierName: string | null;
  @Prop({ type: String, default: null }) declare supplierTrn: string | null;
  @Prop({ type: String, default: null }) declare documentNumber: string | null;
  @Prop({ type: String, default: null }) declare documentDate: string | null;
  @Prop({ type: String, default: null }) declare referenceNumber: string | null;
  @Prop({ type: String, default: null }) declare unit: string | null;
  @Prop({ type: Number, default: null }) declare unitPrice: number | null;

  // Job Card Reference (optional, for stock-out tracking)
  @Prop({ type: String, default: null }) declare jobCardReference: string | null;

  // Expiry selected for stock-out when one batch number has multiple expiry dates.
  @Prop({ type: String, default: null }) declare expiryDate: string | null;

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

export const StockTransactionSchema = SchemaFactory.createForClass(StockTransaction);
StockTransactionSchema.index({ approvalStatus: 1 });
