import mongoose from "mongoose";

const urlRegex =
  /^(https?:\/\/)([\w-]+\.)+[\w-]+(\/[\w\-._~:/?#[\]@!$&'()*+,;=%]*)?$/i;

const directorySchema = new mongoose.Schema(
  {
    submittedBy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },

    companyName: { type: String, required: true },

    companyUrl: {
      type: String,
      required: true,
      unique: true,
      validate: { validator: (v) => urlRegex.test(v), message: "Invalid URL." },
    },

    contactEmail: {
      type: String,
      required: true,
    },

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

    profile: {
      type: String,
      enum: ["freelancer", "agency"],
      required: true,
    },

    openTo: {
      type: String,
      required: true,
    },

    foundingYear: { type: Number, required: true },
    totalEmployees: { type: String, required: true },

    Tagline: {
      type: String,
      maxlength: 150,
    },

    Description: {
      type: String,
      maxlength: 1500,
    },

    budget: { type: String, required: true },

    languages: { type: [String], default: [] },

    coverImage: { type: String, required: true },

    // Submission status - for two-phase payment flow
    status: {
      type: String,
      enum: ['pending_payment', 'published', 'payment_failed'],
      default: 'pending_payment',
      required: true,
    },

    // Payment tracking fields
    paymentOrderID: {
      type: String,
      required: false,
      unique: true,
      sparse: true, // Allows multiple null values
    },
    paymentStatus: {
      type: String,
      enum: ["COMPLETED", "APPROVED", "PENDING", "FAILED", "FREE_COUPON"],
      required: false,
      default: "PENDING",
    },
    paymentAmount: {
      type: Number,
      required: false,
    },
    paymentCurrency: {
      type: String,
      required: false,
      default: "USD",
    },
    payerEmail: {
      type: String,
      required: false,
    },
    payerName: {
      type: String,
      required: false,
    },
    paymentDate: {
      type: Date,
      required: false,
    },
    paymentVerified: {
      type: Boolean,
      default: false,
    },
    // Coupon fields for free submissions
    couponCode: {
      type: String,
      required: false,
    },
    isFreeSubmission: {
      type: Boolean,
      default: false,
    },
  },
  { timestamps: true }
);

const Directory = mongoose.model("Directory", directorySchema);
export default Directory;
