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

export type StockInvoiceDocument = StockInvoice & Document;

/**
 * Tax invoice data extracted by Royal AI and saved alongside a
 * Strategic Stock Movement Sheet. Linked to the sheet via sheetId.
 */
@Schema({ collection: "stock_invoices", timestamps: false })
export class StockInvoice {
  /** Reference back to the StockMovementSheet */
  @Prop({ type: Types.ObjectId, ref: "StockMovementSheet", default: null })
  declare sheetId: Types.ObjectId | null;

  // Core invoice fields
  @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 warehouseName: string | null;

  // Item info from invoice
  @Prop({ type: String, default: null }) declare itemCode: string | null;
  @Prop({ type: String, default: null }) declare itemName: string | null;
  @Prop({ type: String, default: null }) declare batchNumber: string | null;
  @Prop({ type: String, default: null }) declare allBatches: string | null;
  @Prop({ type: String, default: null }) declare expiryDate: string | null;
  @Prop({ type: Number, default: null }) declare quantityMt: number | null;
  @Prop({ type: String, default: null }) declare unit: string | null;
  @Prop({ type: Number, default: null }) declare unitPrice: number | null;

  // Supplier / buyer
  @Prop({ type: String, default: null }) declare supplierName: string | null;
  @Prop({ type: String, default: null }) declare supplierTrn: string | null;
  @Prop({ type: String, default: null }) declare buyerName: string | null;
  @Prop({ type: String, default: null }) declare buyerTrn: string | null;

  // Financial
  @Prop({ type: Number, default: null }) declare totalAmount: number | null;
  @Prop({ type: Number, default: null }) declare vatAmount: number | null;
  @Prop({ type: Number, default: null }) declare netAmount: number | null;
  @Prop({ type: String, default: null }) declare currency: string | null;
  @Prop({ type: String, default: null }) declare paymentTerms: string | null;
  @Prop({ type: String, default: null }) declare dueDate: string | null;

  @Prop({ type: String, default: null }) declare submittedBy: string | null;
  @Prop({ required: true }) declare createdAt: string;
}

export const StockInvoiceSchema = SchemaFactory.createForClass(StockInvoice);
StockInvoiceSchema.index({ sheetId: 1 });
