import mongoose from "mongoose";

const submitAiWebsiteSchema = new mongoose.Schema(
  {
    submittedBy: {
      type: mongoose.Schema.Types.ObjectId,  // ObjectId that refers to WebsiteSubmission model
      ref: 'User',  // Reference to the User model
      required: true,
    },
    websiteUrl: {
      type: String,
      required: true,
      unique: true,
      match: /^(https?:\/\/)([\w-]+\.)+[\w-]+(\/[\w\-._~:/?#[\]@!$&'()*+,;=%]*)?$/i, // URL validation
    },

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

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

    description: {
      type: String,
      maxlength: 3000,
      required: true,
    },

    email: {
      type: String,
      required: true,
      match: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/,
    },

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

    category: {
      type: [String],
      required: true,
    },

    type: {
      type: [String],
      default: ['AI Website'],
    },

    pricingOption: {
      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 information
    paymentOrderID: {
      type: String,
      unique: true,
      sparse: true, // Allows multiple null values but unique non-null values
    },
    paymentStatus: {
      type: String,
      enum: ['COMPLETED', 'APPROVED', 'PENDING', 'FREE_COUPON'],
    },
    paymentAmount: {
      type: Number,
    },
    paymentCurrency: {
      type: String,
      default: 'USD',
    },
    payerEmail: {
      type: String,
    },
    payerName: {
      type: String,
    },
    paymentDate: {
      type: Date,
    },
    paymentVerified: {
      type: Boolean,
      default: false,
    },
    // Coupon fields for free submissions
    couponCode: {
      type: String,
      required: false,
    },
    isFreeSubmission: {
      type: Boolean,
      default: false,
    },
  },
  {
    timestamps: true,
    collection: 'submitaiwebsites' // Explicitly set collection name
  }
);

const SubmitAiWebsite = mongoose.models.SubmitAiWebsite || mongoose.model("SubmitAiWebsite", submitAiWebsiteSchema);
export default SubmitAiWebsite;
