import dotenv from "dotenv";
dotenv.config();
import mongoose from "mongoose";

const TaskSchema = new mongoose.Schema(
  {
    taskId: {
      type: String,
      unique: true,
      required: true,
    },
    task: {
      type: String,
      required: true,
      enum: ["Visit RD/PD", "Update Sales Data", "Update Inventory Data", "Collect KYC"],
    },
    note: {
      type: String,
      required: function () {
        return this.task === "Collect KYC" || this.task === "Visit RD/PD";
      },
    },
    taskStatus: {
      type: String,
      required: true,
      enum: ["New", "Pending", "Completed"],
      default: "New",
    },
    taskPriority: {
      type: String,
      required: true,
      enum: ["Low", "Medium", "High"],
    },
    taskDueDate: {
      type: Date, // Change to Date
      required: true,
    },
    taskAssignedTo: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "SalesCoOrdinator",
      required: true,
    },
    taskAssignedBy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "TerritoryManager",
      required: true,
    },
    addedFor: {
      type: String,
      enum: ['PrincipalDistributor', 'RetailDistributor'],
      required: function () {
        return this.task === "Update Inventory Data" || this.task === "Visit RD/PD" || this.task === "Update Sales Data";
      },
    },
    addedForId: {
      type: mongoose.Schema.Types.ObjectId,
      refPath: 'addedFor',
      required: function () {
        return this.task === "Update Inventory Data" || this.task === "Visit RD/PD" || this.task === "Update Sales Data";
      },
    },
    tradename: {
      type: String,
      required: function () {
        return this.task === "Update Inventory Data" || this.task === "Visit RD/PD" || this.task === "Update Sales Data";
      },
    },
  },
  { timestamps: true }
);

const Task = mongoose.model("Task", TaskSchema);

export default Task;
