import mongoose from "mongoose";

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

const settingProfileSchema = new mongoose.Schema(
  {
    submittedBy: {
      type: mongoose.Schema.Types.ObjectId,  // ObjectId that refers to User model
      ref: 'User',  // Reference to the User model
      required: true,
      unique: true,  // Each user can only have ONE profile
    },
    username: { type: String, required: true },  // No unique constraint - submittedBy is unique
    displayName: { type: String, required: true },
    url: {
      type: String,
      sparse: true,  // Allow null but still enforce uniqueness on non-null values
      validate: { validator: (v) => !v || urlRegex.test(v), message: "Invalid URL." },
    },
    profile: {
      type: String,
      required: true,
    },
    country: { type: String, required: true },
    profilePhoto: { type: String, default: "" },
    facebook: {
      type: String,
      validate: { validator: (v) => !v || urlRegex.test(v), message: "Invalid URL." },
    },
    instagram: {
      type: String,
      validate: { validator: (v) => !v || urlRegex.test(v), message: "Invalid URL." },
    },
    twitter: {
      type: String,
      validate: { validator: (v) => !v || urlRegex.test(v), message: "Invalid URL." },
    },
    linkedin: {
      type: String,
      validate: { validator: (v) => !v || urlRegex.test(v), message: "Invalid URL." },
    },
    tiktok: {
      type: String,
      validate: { validator: (v) => !v || urlRegex.test(v), message: "Invalid URL." },
    },
    youtube: {
      type: String,
      validate: { validator: (v) => !v || urlRegex.test(v), message: "Invalid URL." },
    },
  },
  { timestamps: true } // Automatically adds createdAt & updatedAt
);

const SettingProfile = mongoose.model("SettingProfile", settingProfileSchema);
export default SettingProfile;
