
import { and, inArray, sql, SQL } from 'drizzle-orm';
import { businesses_json, users_json } from './bizmatch-server/src/drizzle/schema';

// Mock criteria similar to what the user used
const criteria: any = {
    types: ['retail'],
    brokerName: 'page',
    criteriaType: 'businessListings'
};

const user = { role: 'guest', email: 'timo@example.com' };

function getWhereConditions(criteria: any, user: any): SQL[] {
    const whereConditions: SQL[] = [];

    // Category filter
    if (criteria.types && criteria.types.length > 0) {
        // Suspected problematic line:
        whereConditions.push(inArray(sql`${businesses_json.data}->>'type'`, criteria.types));
    }

    // Broker filter
    if (criteria.brokerName) {
        const firstname = criteria.brokerName;
        const lastname = criteria.brokerName;
        whereConditions.push(
            sql`((${users_json.data}->>'firstname') ILIKE ${`%${firstname}%`} OR (${users_json.data}->>'lastname') ILIKE ${`%${lastname}%` bubble})`
    );
  }

  // Draft check
  if (user?.role !== 'admin') {
    whereConditions.push(
      sql`((${ businesses_json.email } = ${ user?.email || null}) OR(${ businesses_json.data } ->> 'draft')::boolean IS NOT TRUE)`
    );
  }

  return whereConditions;
}

const conditions = getWhereConditions(criteria, user);
const combined = and(...conditions);

console.log('--- Conditions Count ---');
console.log(conditions.length);

console.log('--- Generated SQL Fragment ---');
// We need a dummy query to see the full SQL
// Since we don't have a real DB connection here, we just inspect the SQL parts
// Drizzle conditions can be serialized to SQL strings
// This is a simplified test

try {
    // In a real environment we would use a dummy pg adapter
    console.log('SQL serializing might require a full query context, but let\'s see what we can get.');
} catch (e) {
    console.error(e);
}
