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

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

export interface PlacePrediction {
  place_id: string;
  description: string;
  structured_formatting?: {
    main_text: string;
    secondary_text: string;
  };
}

/**
 * Autocomplete for street addresses using OpenStreetMap Nominatim API (free, no API key required)
 */
export async function autocompleteAddress(
  input: string,
  country?: string,
  sessionToken?: string,
): Promise<ActionResult<PlacePrediction[]>> {
  return authedAction<PlacePrediction[]>(async (_session) => {
    if (!input) throw new Error('Missing input for autocomplete');

    const params = new URLSearchParams({
      q: input,
      format: 'json',
      limit: '5',
      addressdetails: '1',
    });

    if (country) {
      params.append('countrycodes', country.toLowerCase());
    }

    const response = await fetch(
      `https://nominatim.openstreetmap.org/search?${params.toString()}`,
      {
        headers: {
          'User-Agent': 'CitrineOS-Operator-UI/1.0',
        },
      },
    );

    if (!response.ok) {
      const errorText = await response.text();
      console.error('Failed to fetch autocomplete suggestions due to error:', errorText);
      throw new Error('Failed to fetch autocomplete suggestions');
    }

    const data = await response.json();

    return data.map((item: any) => ({
      place_id: item.place_id?.toString() || '',
      description: item.display_name || '',
      structured_formatting: {
        main_text: item.name || item.display_name?.split(',')[0] || '',
        secondary_text: item.display_name?.split(',').slice(1).join(',').trim() || '',
      },
    }));
  });
}
