import {
  expandSearchTerms,
  categorySlugsMatchingSearch,
} from '@ehandyhire/shared';

/** Prisma `OR` clauses for bilingual worker text + skill search. */
export function workerSearchOrClauses(rawSearch: string): Record<string, unknown>[] {
  const terms = expandSearchTerms(rawSearch).filter((t) => t.length >= 3);
  const slugs = categorySlugsMatchingSearch(rawSearch);
  if (terms.length === 0 && slugs.length === 0) return [];

  const or: Record<string, unknown>[] = [];

  for (const term of terms) {
    or.push(
      { headline: { contains: term } },
      { bio: { contains: term } },
      { otherSkills: { contains: term } },
      { displayName: { contains: term } },
      { user: { firstName: { contains: term } } },
      { user: { lastName: { contains: term } } },
      { skills: { some: { category: { name: { contains: term } } } } }
    );
  }

  if (slugs.length > 0) {
    or.push({ skills: { some: { category: { slug: { in: slugs } } } } });
  }

  return or;
}

/** Prisma `OR` clauses for bilingual category search. */
export function categorySearchOrClauses(rawSearch: string): Record<string, unknown>[] {
  const terms = expandSearchTerms(rawSearch).filter((t) => t.length >= 3);
  const slugs = categorySlugsMatchingSearch(rawSearch);
  if (terms.length === 0 && slugs.length === 0) return [];

  const or: Record<string, unknown>[] = [];

  for (const term of terms) {
    or.push({ name: { contains: term } }, { description: { contains: term } });
  }

  if (slugs.length > 0) {
    or.push({ slug: { in: slugs } });
  }

  return or;
}

/** Prisma `OR` clauses for bilingual job title/description/category search. */
export function jobSearchOrClauses(rawSearch: string): Record<string, unknown>[] {
  const terms = expandSearchTerms(rawSearch).filter((t) => t.length >= 3);
  const slugs = categorySlugsMatchingSearch(rawSearch);
  if (terms.length === 0 && slugs.length === 0) return [];

  const or: Record<string, unknown>[] = [];

  for (const term of terms) {
    or.push(
      { title: { contains: term } },
      { description: { contains: term } },
      { category: { name: { contains: term } } }
    );
  }

  if (slugs.length > 0) {
    or.push({ category: { slug: { in: slugs } } });
  }

  return or;
}
