import type { FormFieldDef } from '@/components/ui/FormDialog';

export interface ApiFieldSchema {
  key: string;
  label: string;
  type: 'text' | 'secret' | 'select' | 'number' | 'textarea';
  required?: boolean;
  optional?: boolean;
  placeholder?: string;
  default?: string | number;
  help?: string;
  section?: string;
  options?: { value: string; label: string }[];
  dlt?: boolean;
}

export interface ApiCatalogEntry {
  type: string;
  name: string;
  description: string;
  channel: string;
  fieldSchema: ApiFieldSchema[];
  dlt?: boolean;
  max_rps?: number;
  cost_per_message?: number;
  help?: string;
}

export function fieldSchemaToFormFields(fields: ApiFieldSchema[]): FormFieldDef[] {
  return (fields || []).map((f) => ({
    key: f.key,
    label: f.label,
    type:
      f.type === 'secret'
        ? 'secret'
        : f.type === 'number'
          ? 'number'
          : f.type === 'select'
            ? 'select'
            : f.type === 'textarea'
              ? 'textarea'
              : 'text',
    required: f.optional ? false : f.required !== false,
    help: f.help,
    placeholder: f.placeholder,
    default: f.default,
    section: f.section,
    options: f.options,
  }));
}

export function splitSecrets(
  values: Record<string, string>,
  fields: ApiFieldSchema[],
): { config: Record<string, string>; secrets: Record<string, string> } {
  const secretKeys = new Set(fields.filter((f) => f.type === 'secret').map((f) => f.key));
  const config: Record<string, string> = {};
  const secrets: Record<string, string> = {};
  for (const [k, v] of Object.entries(values)) {
    // Display name is sent separately on create/update — never fold into provider config.
    if (k === 'name') continue;
    if (!v) continue;
    if (secretKeys.has(k)) secrets[k] = v;
    else config[k] = v;
  }
  return { config, secrets };
}
