import { Injectable } from '@angular/core';

export type WeatherPoint = {
  date_time: string;
  temperature?: number;
  humidity?: number;
  pressure?: number;
  wind_speed?: number;
  wind_direction?: number;
  rainfall?: number;
  rain_total?: number;
  light?: number;
  uv?: number;
};

export type ForecastPoint = WeatherPoint & {
  provider?: string;
  issued_at?: string;
  precip_prob?: number;
  lead_hours?: number;
};

@Injectable({ providedIn: 'root' })
export class ApiService {
  async getStatus(): Promise<{ online_devices: number; server_time: string } | null> {
    try { const r = await fetch('/api/system/status'); return await r.json(); } catch { return null; }
  }

  async getStations(): Promise<any[]> {
    try { const r = await fetch('/api/stations'); return await r.json(); } catch { return []; }
  }

  async getHistory(hexId: string, from: string, to: string, interval: string): Promise<WeatherPoint[]> {
    const params = new URLSearchParams({ hex_id: hexId, start_time: from, end_time: to, interval });
    const r = await fetch(`/api/data?${params.toString()}`);
    if (!r.ok) return [];
    return await r.json();
  }

  async getForecast(stationId: string, from: string, to: string, provider = '', versions = 1): Promise<ForecastPoint[]> {
    const params = new URLSearchParams({ station_id: stationId, from, to, provider, versions: String(versions) });
    const r = await fetch(`/api/forecast?${params.toString()}`);
    if (!r.ok) return [];
    return await r.json();
  }
}
