'use client';

// Typesense client for marketplace search
// Collections: crew_profiles, vendor_profiles

export interface TypesenseCrewProfile {
  id: string;
  name: string;
  location: string;
  skills: string[];
  union_status: string;
  day_rate: number;
  bio: string;
  slug: string;
  featured: boolean;
  headshot_url?: string;
}

export interface TypesenseVendorProfile {
  id: string;
  company_name: string;
  location: string;
  category: string;
  description: string;
  slug: string;
  featured: boolean;
  logo_url?: string;
}

export interface SearchFilters {
  type?: 'crew' | 'vendor' | 'all';
  location?: string;
  skills?: string[];
  category?: string;
  union_status?: string;
  day_rate_min?: number;
  day_rate_max?: number;
  featured_only?: boolean;
  query?: string;
  page?: number;
  per_page?: number;
}

export interface SearchResult {
  hits: Array<{
    document: TypesenseCrewProfile | TypesenseVendorProfile;
    highlight?: Record<string, any>;
  }>;
  found: number;
  page: number;
  out_of: number;
}

const TYPESENSE_HOST = process.env.NEXT_PUBLIC_TYPESENSE_HOST || '';
const TYPESENSE_PORT = process.env.NEXT_PUBLIC_TYPESENSE_PORT || '8108';
const TYPESENSE_PROTOCOL = process.env.NEXT_PUBLIC_TYPESENSE_PROTOCOL || 'http';
const TYPESENSE_API_KEY = process.env.NEXT_PUBLIC_TYPESENSE_SEARCH_KEY || '';

function buildBaseUrl(): string {
  return `${TYPESENSE_PROTOCOL}://${TYPESENSE_HOST}:${TYPESENSE_PORT}`;
}

export async function searchProfiles(filters: SearchFilters): Promise<{
  crew: SearchResult | null;
  vendors: SearchResult | null;
  error?: string;
}> {
  if (!TYPESENSE_HOST) {
    return { crew: null, vendors: null, error: 'Search service not configured' };
  }

  const q = filters.query?.trim() || '*';
  const page = filters.page || 1;
  const per_page = filters.per_page || 20;

  try {
    const results: { crew: SearchResult | null; vendors: SearchResult | null } = {
      crew: null,
      vendors: null,
    };

    const searchType = filters.type || 'all';

    if (searchType === 'all' || searchType === 'crew') {
      const crewParams = new URLSearchParams({
        q,
        query_by: 'name,skills,bio,location',
        page: String(page),
        per_page: String(per_page),
      });

      const filterParts: string[] = [];
      if (filters.union_status) filterParts.push(`union_status:=${filters.union_status}`);
      if (filters.day_rate_min) filterParts.push(`day_rate:>=${filters.day_rate_min}`);
      if (filters.day_rate_max) filterParts.push(`day_rate:<=${filters.day_rate_max}`);
      if (filters.featured_only) filterParts.push('featured:=true');
      if (filterParts.length) crewParams.set('filter_by', filterParts.join(' && '));

      const crewRes = await fetch(
        `${buildBaseUrl()}/collections/crew_profiles/documents/search?${crewParams}`,
        { headers: { 'X-TYPESENSE-API-KEY': TYPESENSE_API_KEY } }
      );
      if (crewRes.ok) results.crew = await crewRes.json();
    }

    if (searchType === 'all' || searchType === 'vendor') {
      const vendorParams = new URLSearchParams({
        q,
        query_by: 'company_name,category,description,location',
        page: String(page),
        per_page: String(per_page),
      });

      const filterParts: string[] = [];
      if (filters.category) filterParts.push(`category:=${filters.category}`);
      if (filters.featured_only) filterParts.push('featured:=true');
      if (filterParts.length) vendorParams.set('filter_by', filterParts.join(' && '));

      const vendorRes = await fetch(
        `${buildBaseUrl()}/collections/vendor_profiles/documents/search?${vendorParams}`,
        { headers: { 'X-TYPESENSE-API-KEY': TYPESENSE_API_KEY } }
      );
      if (vendorRes.ok) results.vendors = await vendorRes.json();
    }

    return results;
  } catch (err: any) {
    return { crew: null, vendors: null, error: err.message };
  }
}
