import { model, Schema } from 'mongoose';
import { paginate, toJSON } from '@/shared/utils/plugins';
import { IUnitJobDoc, IUnitJobModel } from './unit-job.interface';

const unitJobSchema = new Schema<IUnitJobDoc>(
  {
    project: {
      type: Schema.Types.ObjectId,
      ref: 'Project',
      required: true,
    },
    jobId: {
      type: String,
      required: true,
    },
    status: {
      type: String,
      enum: ['pending', 'processing', 'completed', 'failed'],
      default: 'pending',
    },
    progress: {
      type: Number,
      default: 0,
      min: 0,
      max: 100,
    },
    totalUnits: {
      type: Number,
      default: 0,
    },
    processedUnits: {
      type: Number,
      default: 0,
    },
    successfulUnits: {
      type: Number,
      default: 0,
    },
    failedUnits: {
      type: Number,
      default: 0,
    },
    errorRecords: [
      {
        row: Number,
        message: String,
      },
    ],
    filePath: {
      type: String,
      required: true,
    },
    fileName: {
      type: String,
      default: '',
    },
    createdBy: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
    updatedBy: {
      type: Schema.Types.ObjectId,
      ref: 'User',
    },
  },
  {
    timestamps: true,
  },
);

unitJobSchema.plugin(toJSON);
unitJobSchema.plugin(paginate);

const UnitJob = model<IUnitJobDoc, IUnitJobModel>('UnitJob', unitJobSchema);

export default UnitJob;
