// SPDX-FileCopyrightText: 2025 Contributors to the CitrineOS Project
//
// SPDX-License-Identifier: Apache-2.0
'use server';

import { authedAction, type ActionResult } from '@lib/utils/action-guard';

export interface PlaceDetailsResponse {
  id: string;
  displayName: {
    text: string;
    languageCode: string;
  };
  formattedAddress: string;
  addressComponents: Array<{
    longText: string;
    shortText: string;
    types: string[];
    languageCode?: string;
  }>;
  location: {
    latitude: number;
    longitude: number;
  };
  plusCode?: {
    globalCode: string;
    compoundCode?: string;
  };
  types?: string[];
}

export async function getPlaceDetails(
  placeId: string,
  sessionToken?: string,
): Promise<ActionResult<PlaceDetailsResponse>> {
  return authedAction(async (_session) => {
    if (!placeId) {
      throw new Error('Place ID is required');
    }

    try {
      // Use Nominatim OSM for place details (free, no API key)
      const url = `https://nominatim.openstreetmap.org/lookup?format=json&osm_ids=${placeId}&addressdetails=1`;
      const response = await fetch(url, {
        headers: { 'User-Agent': 'CitrineOS-Operator-UI/1.0' },
      });

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

      const data = await response.json();
      if (data && data.length > 0) {
        const place = data[0];
        return {
          id: place.place_id?.toString() || placeId,
          displayName: { text: place.display_name || '', languageCode: 'en' },
          formattedAddress: place.display_name || '',
          addressComponents: [],
          location: {
            latitude: parseFloat(place.lat) || 0,
            longitude: parseFloat(place.lon) || 0,
          },
          types: place.type ? [place.type] : [],
        };
      }

      return {
        id: placeId,
        displayName: { text: '', languageCode: 'en' },
        formattedAddress: '',
        addressComponents: [],
        location: { latitude: 0, longitude: 0 },
      };
    } catch (error) {
      console.error('getPlaceDetails error:', error);
      return {
        id: placeId,
        displayName: { text: '', languageCode: 'en' },
        formattedAddress: '',
        addressComponents: [],
        location: { latitude: 0, longitude: 0 },
      };
    }
  });
}
