// src/models/drone-work-order.ts
// Copyright (C) 2025 DTP Technologies, LLC
// All Rights Reserved

import { Types, Schema, Document, model } from "mongoose";

import { IUser } from "./user.js";
import { IDrone } from "./drone.js";

export enum DroneWorkOrderStatus {
  Pending = "pending",
  InProgress = "in_progress",
  Completed = "completed",
  Failed = "failed",
}

export interface IDroneWorkOrder extends Document {
  _id: Types.ObjectId;
  createdAt: Date;
  finishedAt: Date;
  user: IUser | Types.ObjectId;
  drone: IDrone | Types.ObjectId;
  title: string;
  instructions: string[];
  notes: string[];
  responseFormat: string;
  response?: string;
  status: DroneWorkOrderStatus;
  errorMessages: string[];
}

const DroneWorkOrderSchema = new Schema<IDroneWorkOrder>({
  createdAt: { type: Date, required: true },
  finishedAt: { type: Date },
  user: { type: Schema.Types.ObjectId, ref: "User", index: 1 },
  drone: { type: Schema.Types.ObjectId, ref: "Drone", index: 1 },
  title: { type: String, required: true },
  instructions: { type: [String], required: true },
  notes: { type: [String], required: false },
  responseFormat: { type: String, required: true },
  status: {
    type: String,
    enum: DroneWorkOrderStatus,
    default: DroneWorkOrderStatus.Pending,
    required: true,
  },
  response: { type: String },
  errorMessages: { type: [String], default: [], required: true },
});

export const DroneWorkOrder = model<IDroneWorkOrder>(
  "DroneWorkOrder",
  DroneWorkOrderSchema,
);
export default DroneWorkOrder;

// Note: Index synchronization is now handled during application startup
// to ensure the database connection is established first.
// See src/lib/db.ts for the syncDatabaseIndexes function.
