const mongoose = require("mongoose");

const taskSchema = new mongoose.Schema(
  {

    taskName: {
      type: String,
      trim: true,
      minlength: 3,
      maxlength: 100,
      default: () => `TASK-${Date.now()}`,
    },
    description: {
      type: String,
      trim: true,
      maxlength: [500, "Description cannot exceed 500 characters"],
    },

    // Customer Details
    customer: {
      name: { type: String, trim: true },
      phone: {
        type: String,
        match: [/^[0-9]{10}$/, "Customer phone must be 10 digits"],
      },
      email: { type: String, trim: true, lowercase: true, default : null },
      address: { type: String, trim: true, default : null },
    },

    // for the future purpose will use the below code and remove aboveone
    // customerId: {
    //   type: mongoose.Schema.Types.ObjectId,
    //   ref: "Customer",
    //   required: true,
    // },
    
    // snapshot 
    customerSnapshot: {
      name: String,
      phone: String,
      address: String,
    },



    dueDate: { type: Date, default: null, },
    scheduledDate: { type: Date, default: null, },
    completedAt: { type: Date, default: null, },

    status: {
      type: String,
      required: [true, "Status is required"],
      enum: [
        "Pending",     // task created
        "Assigned",    // assigned to agent
        "Accepted",    // agent accepted
        "Rejected",   // agent rejected
        "In Progress", // work started
        "Overdue",     // SLA breached
        "Completed",   // work done
        "Closed"       // admin closed
      ],
      default: "Pending",
    },

    priority: {
      type: String,
      required: [true, "Priority is required"],
      enum: ["Low", "Medium", "High", "Critical"],
      default: "Medium",
    },
    // sla: { type: String, required: [true, "SLA is required"], trim: true, default : null, },
    sla: {
      type: String,
      trim: true,
      default: null,
    },

    // Agent work tracking
    workStartedAt: { type: Date, default: null },
    workCompletedAt: { type: Date, default: null },
    completionRemarks: {
      type: String,
      trim: true,
    },
    completionImages: {
      type: [String], // Array of image URLs/paths
      default: [],
    },

    workStartLocation: {
      lat: { type: Number },
      lng: { type: Number },
    },

    workEndLocation: {
      lat: { type: Number },
      lng: { type: Number },
    },

    isRevoked: { type: Boolean, default: false },

    // Assignment Tracking
    assignedTo: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
    assignedBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
    assignmentHistory: [
      {
        assignedTo: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
        assignedBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
        assignedAt: { type: Date, default: Date.now },
        revokedAt: { type: Date, default: null },
        previousStatus: {
          type: String,
          enum: ["Pending",
            "Assigned",
            "Accepted",
            "Rejected",
            "In Progress",
            "Overdue",
            "Completed",
            "Closed",],
        },
        newStatus: {
          type: String,
          enum: [
            "Pending",
            "Assigned",
            "Accepted",
            "Rejected",
            "In Progress",
            "Overdue",
            "Completed",
            "Closed",
          ],
          required: true,
        },
      },
    ],

    // Task Events for Timeline / Dashboard
    taskEvents: [
      {
        type: {
          type: String,
          enum: [
            "Created",
            "Assigned",
            "IssueRaised",
            "In Progress",
            "Accepted",
            "Rejected",
            "Reassigned",
            "Revoked",
            "Completed",
          ],
        },
        details: String,
        by: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
        at: { type: Date, default: Date.now },
        default: [],
      },
    ],

    // below feilds related to agent
    acceptedAt: { type: Date, default: null },
    rejectedAt: { type: Date, default: null },
    rejectionReason: { type: String, default: null },


    // Location
    location: { type: String, trim: true },

    // Recurrence
    recurrence: {
      type: { type: String, default: "None" },
      interval: { type: Number, default: 1 },
      endDate: { type: Date, default: null },
      nextOccurrence: { type: Date, default: null },
    },

    service: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Service",
      required: true,
    },

    serviceName: {
      type: String,
      required: true,
      trim: true,
    },

    serviceCost: {
      type: Number,
      required: true,
    },

    serviceSnapshotAt: {
      type: Date,
      default: Date.now,
    },


    // Attachments & Comments
    attachments: [
      {
        fileName: String,
        fileUrl: String,
        // optional
        fileType: String,
        fileSize: Number,
        uploadedAt: { type: Date, default: Date.now },
      },
    ],
    comments: [
      {
        text: String,
        commentedBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
        commentedAt: { type: Date, default: Date.now },
      },
    ],

    // Organization & Audit
    orgId: { type: mongoose.Schema.Types.ObjectId, ref: "Organization", required: true },
    createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
    updatedBy: { type: mongoose.Schema.Types.ObjectId, ref: "User", default: null },
    // updatedAt: { type: Date, default: null },
    isDeleted: { type: Boolean, default: false },

    // Optional Metrics (for Dashboard)
    timesReassigned: { type: Number, default: 0 },
    overdue: { type: Boolean, default: false },
  },
  {
    timestamps: true

  }
);

module.exports = mongoose.model("Task", taskSchema);
