import mongoose, { Document, Schema, StringSchemaDefinition, Types } from 'mongoose';

import { Defect } from "@/app/lib/defect.enum";
import { Product } from "@/app/lib/product.enum";
import { Bin } from '@/app/lib/bin.enum';

import { Farm } from './farm';
import { Processor } from './processor';

export interface Binned {
    bin: Bin;
    date: string;
    farm?: StringSchemaDefinition;
    operator: string;
    processor: StringSchemaDefinition;
    product: Product;
    reason?: Defect;
    weight: number;
}

export type BinnedDocument = Binned & Document;

export type PopulatedBinned = Omit<Binned, 'farm' | 'processor'> & {
    farm: Farm;
    processor: Processor;
};

const BinnedSchema = new Schema<BinnedDocument>(
    {
        bin: { type: Number, enum: Bin, required: true },
        farm: { type: Types.ObjectId, ref: 'Farm' },
        operator: { type: String, required: true },
        date: { type: String, required: true },
        processor: { type: Types.ObjectId, ref: 'Processor' },
        product: { type: String, enum: Object.keys(Product) },
        reason: { type: Number, enum: Defect },
        weight: { type: Number }
    },
    {
        minimize: true,
        timestamps: true,
    },
);

export default mongoose.models?.Binned || mongoose.model<BinnedDocument>('Binned', BinnedSchema);
