-- Update check_database_integrity to check all tables
CREATE OR REPLACE FUNCTION public.check_database_integrity()
RETURNS jsonb
SECURITY DEFINER
AS $$
DECLARE
  tables_to_check text[] := ARRAY[
    'users',
    'settings',
    'companies',
    'categories',
    'products',
    'product_modules',
    'orders',
    'profiles',
    'end_customers',
    'licenses',
    'pos_modules'
  ];
  t text;
  t_exists boolean;
  t_count bigint;
  tables_result jsonb := jsonb_build_object();
  fk_errors_count bigint := 0;
  result jsonb;
BEGIN
  FOREACH t IN ARRAY tables_to_check LOOP
    SELECT EXISTS (
      SELECT 1 FROM pg_tables WHERE schemaname = 'public' AND tablename = t
    ) INTO t_exists;
    
    t_count := 0;
    IF t_exists THEN
      EXECUTE format('SELECT count(*) FROM public.%I', t) INTO t_count;
    END IF;
    
    tables_result := tables_result || jsonb_build_object(t, jsonb_build_object('exists', t_exists, 'count', t_count));
  END LOOP;

  -- Count foreign key errors (orphaned licenses)
  SELECT EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'public' AND tablename = 'licenses') INTO t_exists;
  IF t_exists THEN
    SELECT EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'public' AND tablename = 'end_customers') INTO t_exists;
    IF t_exists THEN
      EXECUTE '
        SELECT count(*)
        FROM public.licenses l
        LEFT JOIN public.end_customers c ON l.end_customer_id = c.id
        WHERE c.id IS NULL AND l.end_customer_id IS NOT NULL
      ' INTO fk_errors_count;
    END IF;
  END IF;

  result := jsonb_build_object(
    'tables', tables_result,
    'errors', jsonb_build_object(
      'foreign_keys', fk_errors_count
    )
  );

  RETURN result;
END;
$$ LANGUAGE plpgsql;
