/**
 * @ai-summary API client for Gas Stations feature
 */

import { apiClient } from '@/core/api/client';
import {
  Station,
  StationSearchRequest,
  StationSearchResponse,
  SavedStation,
  SaveStationData,
  ApiError
} from '../types/stations.types';

const API_BASE = '/stations';

class StationsApiClient {
  /**
   * Search for nearby gas stations
   * @param request Search parameters (latitude, longitude, radius)
   * @returns Promise with stations found
   */
  async searchStations(request: StationSearchRequest): Promise<Station[]> {
    try {
      const response = await apiClient.post<StationSearchResponse>(
        `${API_BASE}/search`,
        {
          latitude: request.latitude,
          longitude: request.longitude,
          radius: request.radius || 5000,
          fuelType: request.fuelType
        }
      );

      return response.data.stations || [];
    } catch (error) {
      console.error('Station search failed:', error);
      throw this.handleError(error);
    }
  }

  /**
   * Save a station to user favorites
   * @param placeId Google Places ID
   * @param data Station metadata (nickname, notes, isFavorite)
   * @returns Saved station record
   */
  async saveStation(
    placeId: string,
    data: SaveStationData
  ): Promise<SavedStation> {
    try {
      const response = await apiClient.post<SavedStation>(
        `${API_BASE}/save`,
        {
          placeId,
          ...data
        }
      );

      return response.data;
    } catch (error) {
      console.error('Save station failed:', error);
      throw this.handleError(error);
    }
  }

  /**
   * Get all saved stations for current user
   * @returns Array of saved stations
   */
  async getSavedStations(): Promise<SavedStation[]> {
    try {
      const response = await apiClient.get<SavedStation[]>(
        `${API_BASE}/saved`
      );

      return response.data || [];
    } catch (error) {
      console.error('Get saved stations failed:', error);
      throw this.handleError(error);
    }
  }

  /**
   * Get a specific saved station
   * @param placeId Google Places ID
   * @returns Saved station details or null
   */
  async getSavedStation(placeId: string): Promise<SavedStation | null> {
    try {
      const response = await apiClient.get<SavedStation>(
        `${API_BASE}/saved/${placeId}`
      );

      return response.data || null;
    } catch (error) {
      if ((error as any)?.response?.status === 404) {
        return null;
      }
      console.error('Get saved station failed:', error);
      throw this.handleError(error);
    }
  }

  /**
   * Delete a saved station
   * @param placeId Google Places ID
   */
  async deleteSavedStation(placeId: string): Promise<void> {
    try {
      await apiClient.delete(`${API_BASE}/saved/${placeId}`);
    } catch (error) {
      console.error('Delete saved station failed:', error);
      throw this.handleError(error);
    }
  }

  /**
   * Update a saved station's metadata
   * @param placeId Google Places ID
   * @param data Updated metadata
   */
  async updateSavedStation(
    placeId: string,
    data: Partial<SaveStationData>
  ): Promise<SavedStation> {
    try {
      const response = await apiClient.patch<SavedStation>(
        `${API_BASE}/saved/${placeId}`,
        data
      );

      return response.data;
    } catch (error) {
      console.error('Update saved station failed:', error);
      throw this.handleError(error);
    }
  }

  /**
   * Handle API errors with proper typing
   */
  private handleError(error: unknown): ApiError {
    const axiosError = error as any;

    if (axiosError?.response?.data) {
      return axiosError.response.data as ApiError;
    }

    if (axiosError?.message) {
      return {
        message: axiosError.message,
        code: 'UNKNOWN_ERROR'
      };
    }

    return {
      message: 'An unexpected error occurred',
      code: 'UNKNOWN_ERROR'
    };
  }
}

export const stationsApi = new StationsApiClient();
