import { getWebhookUrl } from '@/lib/config';

export type TemplateUploadResult = {
  success: boolean;
  message?: string;
  [key: string]: any;
};

export type TemplateRecord = {
  id: string | number;
  name: string;
  description?: string;
  type?: string;
  preview_img?: string;
  [key: string]: any;
};

export const uploadTemplateZip = async (apiFetch: Function, file: File): Promise<TemplateUploadResult> => {
  const formData = new FormData();
  formData.append('file', file);

  const response = await apiFetch(`${getWebhookUrl()}/template`, {
    method: 'POST',
    body: formData,
    skipAuthHandling: true,
  });

  const contentType = response.headers.get('content-type') || '';

  if (contentType.includes('application/json')) {
    const raw = await response.json();
    const data = Array.isArray(raw) ? raw[0] ?? {} : raw ?? {};
    return {
      success: data.success !== false,
      ...data,
    };
  }

  const text = await response.text();
  const trimmed = (text || '').trim();
  return {
    success: true,
    message: trimmed || undefined,
  };
};

export const fetchTemplates = async (apiFetch: Function): Promise<TemplateRecord[]> => {
  const response = await apiFetch(`${getWebhookUrl()}/templates`, {
    method: 'GET',
    headers: { 'Content-Type': 'application/json' },
    skipAuthHandling: true,
  });

  const raw = await response.json();

  const data: any =
    typeof raw === 'string'
      ? (() => {
          try {
            return JSON.parse(raw);
          } catch {
            return raw;
          }
        })()
      : raw;

  return Array.isArray(data) ? (data as TemplateRecord[]) : data ? ([data] as TemplateRecord[]) : [];
};
