// models/formModel.js
const mongoose = require("mongoose");

const fieldSchema = new mongoose.Schema(
  {
    fieldId: {
      type: String,
      required: [true, "Field ID is required"],
      trim: true,
    },
    label: {
      type: String,
      required: [true, "Field label is required"],
      trim: true,
      minlength: [2, "Label must be at least 2 characters long"],
      maxlength: [100, "Label cannot exceed 100 characters"],
    },
    type: {
      type: String,
      required: [true, "Field type is required"],
      enum: [
        "text",
        "number",
        "tel",
        "email",
        "password",
        "textarea",
        "dropdown",
        "radio",
        "checkbox",
        "date",
        "url",
        "time",
        "file",
        "image",
      ],
    },
    placeholder: {
      type: String,
      trim: true,
      maxlength: [200, "Placeholder cannot exceed 200 characters"],
    },
    required: {
      type: Boolean,
      default: false,
    },
    options: {
      type: [String], // only used for dropdown, radio, checkbox
      validate: {
        validator: function (val) {
          // Ensure options exist if type requires them
          if (["dropdown", "radio"].includes(this.type)) {
            return Array.isArray(val) && val.length > 0;
          }
          return true;
        },
        message: "Options are required for dropdown and radio fields",
      },
    },
  },
  { _id: false } // don’t need separate ObjectIds for fields
);

const formSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, "Form name is required"],
      trim: true,
      minlength: [3, "Form name must be at least 3 characters long"],
      maxlength: [100, "Form name cannot exceed 100 characters"],
    },
    description: {
      type: String,
      trim: true,
      maxlength: [500, "Description cannot exceed 500 characters"],
      default: null,
    },
    status: {
      type: Boolean,
      default: true,
    },
     isDeleted: {
      type: Boolean,
      default: false, // soft delete flag
    },
    orgId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Organization",
      required: [true, "Organization ID is required"],
    },
    createdBy: {
      type: String,
      trim: true,
      default: null,
    },
    updatedBy: {
      type: String,
      trim: true,
      default: null,
    },
    fields: {
      type: [fieldSchema],
      validate: {
        validator: function (val) {
          return Array.isArray(val) && val.length > 0;
        },
        message: "At least one field is required in a form",
      },
    },
  },
  {
    timestamps: true, // auto adds createdAt & updatedAt
  }
);

module.exports = mongoose.model("Form", formSchema);
