import { Trip, TripPlace, TripDataRaw, TripDayRaw, TripPlaceRaw } from '@/types/trip-ui';

/**
 * Transforms raw trip data from the API into a standardized Trip object for the UI.
 * Unifies differences between store and context implementations.
 * Uses Turkish (tr-TR) locale for dates.
 */
export const transformTripData = (tripData: TripDataRaw): Trip => {
  return {
    id: tripData.id,
    title: tripData.title,
    destination: tripData.destination || 'Gidilecek Yer',
    startDate: tripData.start_date || new Date().toISOString(),
    endDate: tripData.end_date || new Date().toISOString(),
    start_date: tripData.start_date || new Date().toISOString(),
    end_date: tripData.end_date || new Date().toISOString(),
    travelers: tripData.number_of_travelers || 2,
    number_of_travelers: tripData.number_of_travelers || 2,
    coverImage: tripData.cover_image || 'https://images.unsplash.com/photo-1469854523086-cc02fe5d8800?q=80&w=2021&auto=format&fit=crop',
    has_balloon: tripData.has_balloon,
    balloon_day_id: tripData.balloon_day_id,
    start_lat: tripData.start_lat,
    start_lng: tripData.start_lng,
    start_location_name: tripData.start_location_name,
    start_location_type: tripData.start_location_type,
    interests: tripData.interests || [],
    created_at: tripData.created_at || new Date().toISOString(),
    updated_at: tripData.updated_at || new Date().toISOString(),
    days: (tripData.trip_days || [])
      .sort((a: TripDayRaw, b: TripDayRaw) => a.day_number - b.day_number)
      .map((day: TripDayRaw) => ({
        id: day.id,
        dayNumber: day.day_number,
        date: day.date || new Date().toISOString().split('T')[0],
        dayName: day.date ? new Date(day.date).toLocaleDateString('tr-TR', { weekday: 'long' }) : 'Gün',
        suggested_tour_slug: day.suggested_tour_slug,
        places: (day.trip_places || [])
          .sort((a: TripPlaceRaw, b: TripPlaceRaw) => a.order_index - b.order_index)
          .map((tp: TripPlaceRaw) => {
            // Handle differences in how Supabase returns place data (could be .place or .places)
            const place = tp.place || tp.places;
            
            return {
              id: place?.id || tp.place_id,
              tripPlaceId: tp.id,
              name: place?.name || 'Bilinmeyen Yer',
              type: place?.type || 'activity',
              duration: place?.duration || tp.duration || '2 saat',
              img: place?.image_url,
              position: {
                lat: Number(place?.latitude || 0),
                lng: Number(place?.longitude || 0),
              },
              rating: place?.rating,
              description: place?.description,
              timeOfDay: tp.time_of_day,
              notes: tp.notes || '',
              order_index: tp.order_index,
            };
          })
          .filter((p: TripPlace) => p.id) as TripPlace[]
      }))
  };
};
