import type {
  ApiResponse,
  ColorInfoRequest,
  ColorInfoData,
  ConvertFormatRequest,
  ConvertFormatData,
  ColorManipulationRequest,
  ColorManipulationData,
  RandomColorsRequest,
  RandomColorsData,
  GradientRequest,
  GradientData,
  HealthData,
  CapabilitiesData,
  PaletteGenerateRequest,
  PaletteGenerateData,
} from './types';
import { colorWASM } from './wasm-client';

export class ColorAPIClient {
  private baseURL: string;

  constructor(baseURL?: string) {
    // Use the Next.js API proxy route for runtime configuration
    // This allows changing the backend API URL without rebuilding
    this.baseURL = baseURL || '/api/color';
  }

  private async request<T>(
    endpoint: string,
    options?: RequestInit
  ): Promise<ApiResponse<T>> {
    // Endpoint already includes /api/v1 prefix on backend,
    // but our proxy route expects paths after /api/v1/
    const url = `${this.baseURL}${endpoint}`;

    try {
      const response = await fetch(url, {
        ...options,
        headers: {
          'Content-Type': 'application/json',
          ...options?.headers,
        },
      });

      const data = await response.json();

      if (!response.ok) {
        return {
          success: false,
          error: data.error || {
            code: 'INTERNAL_ERROR',
            message: 'An unknown error occurred',
          },
        };
      }

      return data;
    } catch (error) {
      return {
        success: false,
        error: {
          code: 'NETWORK_ERROR',
          message: error instanceof Error ? error.message : 'Network request failed',
        },
      };
    }
  }

  // Color Information
  async getColorInfo(request: ColorInfoRequest): Promise<ApiResponse<ColorInfoData>> {
    return this.request<ColorInfoData>('/colors/info', {
      method: 'POST',
      body: JSON.stringify(request),
    });
  }

  // Format Conversion
  async convertFormat(request: ConvertFormatRequest): Promise<ApiResponse<ConvertFormatData>> {
    return this.request<ConvertFormatData>('/colors/convert', {
      method: 'POST',
      body: JSON.stringify(request),
    });
  }

  // Color Manipulation
  async lighten(request: ColorManipulationRequest): Promise<ApiResponse<ColorManipulationData>> {
    return this.request<ColorManipulationData>('/colors/lighten', {
      method: 'POST',
      body: JSON.stringify(request),
    });
  }

  async darken(request: ColorManipulationRequest): Promise<ApiResponse<ColorManipulationData>> {
    return this.request<ColorManipulationData>('/colors/darken', {
      method: 'POST',
      body: JSON.stringify(request),
    });
  }

  async saturate(request: ColorManipulationRequest): Promise<ApiResponse<ColorManipulationData>> {
    return this.request<ColorManipulationData>('/colors/saturate', {
      method: 'POST',
      body: JSON.stringify(request),
    });
  }

  async desaturate(request: ColorManipulationRequest): Promise<ApiResponse<ColorManipulationData>> {
    return this.request<ColorManipulationData>('/colors/desaturate', {
      method: 'POST',
      body: JSON.stringify(request),
    });
  }

  async rotate(request: ColorManipulationRequest): Promise<ApiResponse<ColorManipulationData>> {
    return this.request<ColorManipulationData>('/colors/rotate', {
      method: 'POST',
      body: JSON.stringify(request),
    });
  }

  async complement(colors: string[]): Promise<ApiResponse<ColorManipulationData>> {
    return this.request<ColorManipulationData>('/colors/complement', {
      method: 'POST',
      body: JSON.stringify({ colors }),
    });
  }

  async grayscale(colors: string[]): Promise<ApiResponse<ColorManipulationData>> {
    return this.request<ColorManipulationData>('/colors/grayscale', {
      method: 'POST',
      body: JSON.stringify({ colors }),
    });
  }

  // Color Generation
  async generateRandom(request: RandomColorsRequest): Promise<ApiResponse<RandomColorsData>> {
    return this.request<RandomColorsData>('/colors/random', {
      method: 'POST',
      body: JSON.stringify(request),
    });
  }

  async generateGradient(request: GradientRequest): Promise<ApiResponse<GradientData>> {
    return this.request<GradientData>('/colors/gradient', {
      method: 'POST',
      body: JSON.stringify(request),
    });
  }

  // System
  async getHealth(): Promise<ApiResponse<HealthData>> {
    return this.request<HealthData>('/health', {
      method: 'GET',
    });
  }

  async getCapabilities(): Promise<ApiResponse<CapabilitiesData>> {
    return this.request<CapabilitiesData>('/capabilities', {
      method: 'GET',
    });
  }

  // Palette Generation
  async generatePalette(request: PaletteGenerateRequest): Promise<ApiResponse<PaletteGenerateData>> {
    return this.request<PaletteGenerateData>('/palettes/generate', {
      method: 'POST',
      body: JSON.stringify(request),
    });
  }
}

// Export singleton instance
// Now using WASM client for zero-latency, offline-first color operations
export const colorAPI = colorWASM;
