// API service for connecting to KiroServices backend
import { Property, MovingService, MapProperty, Booking } from '../types';

const API_BASE_URL = 'https://your-replit-url.replit.app'; // Update this with actual URL

class ApiService {
  private async request<T>(endpoint: string, options?: RequestInit): Promise<T> {
    try {
      const response = await fetch(`${API_BASE_URL}${endpoint}`, {
        headers: {
          'Content-Type': 'application/json',
          ...options?.headers,
        },
        ...options,
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      return await response.json();
    } catch (error) {
      console.error('API request failed:', error);
      throw error;
    }
  }

  // Property endpoints
  async getProperties(filters?: { type?: string; location?: string; maxPrice?: string }): Promise<Property[]> {
    const params = new URLSearchParams();
    if (filters?.type) params.append('type', filters.type);
    if (filters?.location) params.append('location', filters.location);
    if (filters?.maxPrice) params.append('maxPrice', filters.maxPrice);
    
    const queryString = params.toString();
    return this.request<Property[]>(`/api/properties${queryString ? `?${queryString}` : ''}`);
  }

  async getProperty(id: string): Promise<Property> {
    return this.request<Property>(`/api/properties/${id}`);
  }

  async getPropertiesForMap(): Promise<MapProperty[]> {
    return this.request<MapProperty[]>('/api/properties/map');
  }

  // Moving services endpoints
  async getMovingServices(): Promise<MovingService[]> {
    return this.request<MovingService[]>('/api/moving-services');
  }

  async getMovingService(id: string): Promise<MovingService> {
    return this.request<MovingService>(`/api/moving-services/${id}`);
  }

  // Booking endpoints
  async createBooking(bookingData: Omit<Booking, 'id' | 'status'>): Promise<Booking> {
    return this.request<Booking>('/api/bookings', {
      method: 'POST',
      body: JSON.stringify(bookingData),
    });
  }

  async getUserBookings(userId: string): Promise<Booking[]> {
    return this.request<Booking[]>(`/api/bookings?userId=${userId}`);
  }

  async updateBooking(id: string, updates: Partial<Booking>): Promise<Booking> {
    return this.request<Booking>(`/api/bookings/${id}`, {
      method: 'PUT',
      body: JSON.stringify(updates),
    });
  }

  // Contact/message endpoints
  async sendMessage(propertyId: string, message: string, contactInfo: { name: string; email: string; phone: string }): Promise<void> {
    await this.request('/api/messages', {
      method: 'POST',
      body: JSON.stringify({
        propertyId,
        message,
        ...contactInfo,
      }),
    });
  }
}

export const apiService = new ApiService();