import { ContactLog } from '@/types';
import { getSupabaseClient } from '@/lib/supabase';
import { getVisibleBatchIds } from '@/services/dataAccessScope';

export async function fetchContactLogs(params?: {
  batchId?: string;
  status?: string;
  search?: string;
}): Promise<ContactLog[]> {
  const supabase = getSupabaseClient();
  const visibleBatchIds = await getVisibleBatchIds({ batchId: params?.batchId });

  if (visibleBatchIds.length === 0) {
    return [];
  }

  let query = supabase
    .from('contact_logs')
    .select('*')
    .order('created_at', { ascending: false });

  query = query.in('batch_id', visibleBatchIds);

  if (params?.status && params.status !== 'all') {
    query = query.eq('status', params.status);
  }
  if (params?.search) {
    query = query.or(`keyword.ilike.%${params.search}%,merchant_name.ilike.%${params.search}%,title.ilike.%${params.search}%`);
  }

  const { data, error } = await query;
  if (error) throw error;
  return (data ?? []) as ContactLog[];
}
