import api from '../core/api';

const DEFAULT_SEED_FIELDS: Record<string, string[]> = {
  branch: ['name'],
  customer: ['first_name', 'last_name'],
  sku: ['type'],
  barcode: [],
  slug: ['title'],
};

const DEFAULT_SEEDS: Record<string, string> = {
  branch: 'branch',
  customer: 'customer',
  sku: 'item',
  slug: 'page',
};

type AutoGenerateConfig = string | { type: string; seedFields?: string[] };

export function autoGenerateSeedFields(field: { autoGenerate?: AutoGenerateConfig }): string[] {
  const type = typeof field.autoGenerate === 'string' ? field.autoGenerate : field.autoGenerate?.type;
  if (!type) return [];

  if (typeof field.autoGenerate === 'object' && field.autoGenerate?.seedFields) {
    return field.autoGenerate.seedFields;
  }

  return DEFAULT_SEED_FIELDS[type] || [];
}

export function buildAutoGenerateSeed(formData: Record<string, unknown>, seedFields: string[], type = ''): string {
  const seed = seedFields
    .map((key) => String(formData?.[key] ?? '').trim())
    .filter(Boolean)
    .join(' ')
    .trim();

  if (seed) return seed;

  return DEFAULT_SEEDS[type] || '';
}

export async function fetchGeneratedCode({
  type,
  seed = '',
  recordId,
  resource,
}: {
  type: string;
  seed?: string;
  recordId?: number | string;
  resource?: string;
}): Promise<string> {
  const params: Record<string, string | number | undefined> = {
    type,
    seed: seed || undefined,
    record_id: recordId || undefined,
  };

  if (type === 'slug' && resource) {
    params.resource = resource;
  }

  const { data } = await api.get<{ code?: string; data?: { code?: string }; message?: string }>('/codes/generate', {
    params,
  });

  const code = data.code ?? data.data?.code;
  if (!code) {
    throw new Error(data.message || 'Server did not return a generated code.');
  }

  return code;
}
