/**
 * Branding API
 * Handles PDF branding configuration management
 */

import { Capacitor } from '@capacitor/core';
import api from './api';

const API_BASE_URL = Capacitor.isNativePlatform()
  ? 'https://veridian.runfoo.run'
  : (import.meta.env.VITE_API_URL || '');

export interface BrandingConfig {
  id: string;
  name: string;
  titleFont?: string;
  bodyFont?: string;
  labelFont?: string;
  primaryColor?: string;
  secondaryColor?: string;
  accentColor?: string;
  logoData?: string;
  createdAt: string;
  updatedAt: string;
}

/**
 * Get all branding configurations
 */
export async function getAllBrandings(): Promise<BrandingConfig[]> {
  const response = await api.get<{ brandings: BrandingConfig[] }>('/branding');
  return response.data.brandings;
}

/**
 * Get a specific branding configuration
 */
export async function getBranding(id: string): Promise<BrandingConfig> {
  const response = await api.get<BrandingConfig>(`/branding/${id}`);
  return response.data;
}

/**
 * Get the default branding configuration
 */
export async function getDefaultBranding(): Promise<BrandingConfig> {
  const response = await api.get<BrandingConfig>('/branding/default');
  return response.data;
}

/**
 * Create or update a branding configuration
 */
export async function saveBranding(
  id: string | undefined,
  data: Partial<BrandingConfig>
): Promise<BrandingConfig> {
  const url = id ? `/branding/${id}` : '/branding';
  const response = await api.post<BrandingConfig>(url, data);
  return response.data;
}

/**
 * Delete a branding configuration
 */
export async function deleteBranding(id: string): Promise<{ success: boolean; message: string }> {
  const response = await api.delete<{ success: boolean; message: string }>(`/branding/${id}`);
  return response.data;
}

/**
 * Register a custom font for PDF generation
 */
export async function registerFont(name: string, fontData: string): Promise<{
  success: boolean;
  font: string;
  message: string;
}> {
  const token = localStorage.getItem('token');
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
  };
  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }

  const response = await fetch(`${API_BASE_URL}/api/pdf/fonts/register`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ name, fontData }),
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Failed to register font');
  }

  return response.json();
}

/**
 * Get list of registered fonts
 */
export async function getRegisteredFonts(): Promise<string[]> {
  const response = await fetch(`${API_BASE_URL}/api/pdf/fonts`);

  if (!response.ok) {
    throw new Error(`Failed to get fonts: ${response.statusText}`);
  }

  const data = await response.json();
  return data.fonts || [];
}

/**
 * Convert a file to base64
 */
export function fileToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      const result = reader.result as string;
      // Remove data URL prefix (e.g., "data:font/ttf;base64,")
      const base64 = result.split(',')[1];
      resolve(base64);
    };
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

/**
 * Convert an image file to base64
 */
export function imageToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      resolve(reader.result as string);
    };
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}
