import { FieldType } from "@capakraken/shared";

export interface CustomFieldFilterInput {
  key: string;
  value: string;
  type: FieldType;
}

export interface DynamicFieldWhereClause {
  path: [string];
  equals?: boolean | number;
  array_contains?: string;
  string_contains?: string;
}

export function buildDynamicFieldWhereClauses(
  filters: readonly CustomFieldFilterInput[] | undefined,
): DynamicFieldWhereClause[] {
  const conditions: DynamicFieldWhereClause[] = [];

  for (const { key, value, type } of filters ?? []) {
    if (!value) continue;

    if (type === FieldType.BOOLEAN) {
      conditions.push({ path: [key], equals: value === "true" });
      continue;
    }

    if (type === FieldType.NUMBER) {
      const parsed = Number.parseFloat(value);
      if (!Number.isNaN(parsed)) {
        conditions.push({ path: [key], equals: parsed });
      }
      continue;
    }

    if (type === FieldType.MULTI_SELECT) {
      conditions.push({ path: [key], array_contains: value });
      continue;
    }

    conditions.push({ path: [key], string_contains: value });
  }

  return conditions;
}
