/**
 * Branding Service
 * Manages custom branding settings for PDF generation
 */

import { randomUUID } from 'crypto';

export interface BrandingConfig {
  id: string;
  name: string;
  // Font references (stored separately)
  titleFont?: string;
  bodyFont?: string;
  labelFont?: string;
  // Colors
  primaryColor?: string;
  secondaryColor?: string;
  accentColor?: string;
  // Logo
  logoData?: string; // base64 encoded image
  // Metadata
  createdAt: Date;
  updatedAt: Date;
}

class BrandingService {
  private configs: Map<string, BrandingConfig> = new Map();

  constructor() {
    this.loadDefaultBranding();
  }

  private loadDefaultBranding() {
    // Create a default branding configuration
    const defaultBranding: BrandingConfig = {
      id: 'default',
      name: 'Default',
      createdAt: new Date(),
      updatedAt: new Date(),
    };
    this.configs.set('default', defaultBranding);
  }

  /**
   * Get a branding configuration by ID
   */
  getBranding(id: string): BrandingConfig | undefined {
    return this.configs.get(id);
  }

  /**
   * Get the default branding configuration
   */
  getDefaultBranding(): BrandingConfig {
    return this.configs.get('default')!;
  }

  /**
   * Create or update a branding configuration
   */
  async saveBranding(config: Partial<BrandingConfig>): Promise<BrandingConfig> {
    const id = config.id || randomUUID();
    const existing = this.configs.get(id);

    const branding: BrandingConfig = {
      id,
      name: config.name || 'Custom Branding',
      titleFont: config.titleFont,
      bodyFont: config.bodyFont,
      labelFont: config.labelFont,
      primaryColor: config.primaryColor,
      secondaryColor: config.secondaryColor,
      accentColor: config.accentColor,
      logoData: config.logoData,
      createdAt: existing?.createdAt || new Date(),
      updatedAt: new Date(),
    };

    this.configs.set(id, branding);

    return branding;
  }

  /**
   * List all branding configurations
   */
  listBrandings(): BrandingConfig[] {
    return Array.from(this.configs.values());
  }

  /**
   * Delete a branding configuration
   */
  async deleteBranding(id: string): Promise<boolean> {
    if (id === 'default') {
      throw new Error('Cannot delete default branding');
    }

    return this.configs.delete(id);
  }
}

export const brandingService = new BrandingService();
