const allowedBrandColors = ["teal", "navy", "indigo", "forest", "clay"];
const reservedHost = /(^|\.)(example\.(com|org|net)|test|invalid|localhost)$/i;

function validPublishedUrl(value) {
  if (!value) {
    return false;
  }

  try {
    const url = new URL(value);
    return url.protocol === "https:" && !reservedHost.test(url.hostname) && !/your-coach/i.test(url.href);
  } catch {
    return false;
  }
}

function validCustomDomain(value) {
  if (!value) {
    return true;
  }

  const hostname = String(value).trim().toLowerCase().replace(/^https?:\/\//, "").split('/')[0];
  return /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(hostname) && !reservedHost.test(hostname);
}

function validateWorkspaceSettings(data) {
  const errors = [];

  if (data.brand_color && !allowedBrandColors.includes(data.brand_color)) {
    errors.push("brand_color_invalid");
  }

  if (data.default_booking_url && !validPublishedUrl(data.default_booking_url)) {
    errors.push("booking_url_invalid");
  }

  if (data.logo_url && !validPublishedUrl(data.logo_url)) {
    errors.push("logo_url_invalid");
  }

  if (data.coach_photo_url && !validPublishedUrl(data.coach_photo_url)) {
    errors.push("coach_photo_url_invalid");
  }

  if (!validCustomDomain(data.custom_domain)) {
    errors.push("custom_domain_invalid");
  }

  if (data.default_reminder_minutes && ![10, 60, 1440].includes(Number(data.default_reminder_minutes))) {
    errors.push("default_reminder_minutes_invalid");
  }

  if (!Array.isArray(data.social_links)) {
    errors.push("social_links_invalid");
  } else if (data.social_links.some((link) => !link || !String(link.label || "").trim() || !validPublishedUrl(link.href))) {
    errors.push("social_links_invalid");
  }

  if (!Array.isArray(data.packages)) {
    errors.push("packages_invalid");
  } else if (data.packages.some((item) => {
    if (!item || !String(item.name || "").trim()) {
      return true;
    }

    return Boolean(item.booking_url) && !validPublishedUrl(item.booking_url);
  })) {
    errors.push("packages_invalid");
  }

  if (!Array.isArray(data.testimonials)) {
    errors.push("testimonials_invalid");
  }

  if (data.published) {
    const practiceName = String(data.practice_name || "").trim();
    const coachName = String(data.coach_name || "").trim();
    const contactEmail = String(data.contact_email || "").trim();
    const coachBio = String(data.coach_bio || "").trim();

    if (!practiceName) {
      errors.push("practice_name_required");
    } else if (/^(demo coaching practice|sample coaching practice|your practice)$/i.test(practiceName)) {
      errors.push("practice_name_placeholder");
    }

    if (!coachName) {
      errors.push("coach_name_required");
    } else if (/^(demo coach|sample coach|your coach)$/i.test(coachName)) {
      errors.push("coach_name_placeholder");
    }

    if (!/^\S+@\S+\.\S+$/.test(contactEmail) || /@example\.(com|org|net)$|\.invalid$/i.test(contactEmail)) {
      errors.push("contact_email_invalid");
    }

    if (coachBio.length < 40) {
      errors.push("coach_bio_required");
    }

    if (!validPublishedUrl(data.default_booking_url)) {
      errors.push("booking_url_required");
    }

    if (!Array.isArray(data.packages) || data.packages.length === 0) {
      errors.push("published_package_required");
    }

    if (!String(data.legal_entity_name || "").trim()) {
      errors.push("legal_entity_name_required");
    }

    if (!/^\S+@\S+\.\S+$/.test(String(data.legal_contact_email || "")) || /@example\.(com|org|net)$|\.invalid$/i.test(String(data.legal_contact_email || ""))) {
      errors.push("legal_contact_email_invalid");
    }

    if (!/^\d{4}-\d{2}-\d{2}$/.test(String(data.legal_terms_effective_date || ""))) {
      errors.push("legal_terms_effective_date_required");
    }

    if (data.legal_review_confirmed !== true) {
      errors.push("legal_review_required");
    }
  }

  return errors;
}

function publicWorkspaceSettings(settings) {
  if (!settings.published) {
    return { published: false };
  }

  const socialLinks = Array.isArray(settings.social_links) ? settings.social_links : [];
  const packages = Array.isArray(settings.packages) ? settings.packages : [];
  const testimonials = Array.isArray(settings.testimonials) ? settings.testimonials : [];

  return {
    practice_name: settings.practice_name,
    logo_url: validPublishedUrl(settings.logo_url) ? settings.logo_url : null,
    coach_name: settings.coach_name,
    coach_photo_url: validPublishedUrl(settings.coach_photo_url) ? settings.coach_photo_url : null,
    coach_bio: settings.coach_bio,
    coach_credentials: settings.coach_credentials,
    coach_niche: settings.coach_niche,
    brand_color: settings.brand_color,
    default_booking_url: validPublishedUrl(settings.default_booking_url) ? settings.default_booking_url : null,
    contact_email: settings.contact_email,
    social_links: socialLinks
      .filter((link) => link && String(link.label || "").trim() && validPublishedUrl(link.href))
      .map((link) => ({ label: String(link.label).trim(), href: link.href })),
    packages: packages.map((item) => ({
      slug: item.slug,
      name: item.name,
      description: item.description,
      duration: item.duration,
      price: item.price,
      cta_label: item.cta_label,
      booking_url: validPublishedUrl(item.booking_url) ? item.booking_url : null,
      items: Array.isArray(item.items) ? item.items.map(String) : [],
    })),
    testimonials: testimonials
      .filter((item) => item && (item.verified === true || item.permission_granted === true))
      .map((item) => ({ quote: item.quote, name: item.name, role: item.role })),
    published: true,
  };
}

module.exports = { allowedBrandColors, validCustomDomain, validPublishedUrl, validateWorkspaceSettings, publicWorkspaceSettings };
