import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

export interface OverpassElementNode {
  type: 'node';
  id: number;
  lat: number;
  lon: number;
}

export interface OverpassElementWay {
  type: 'way';
  id: number;
  geometry?: Array<{ lat: number; lon: number }>;
}

export type OverpassElement = OverpassElementNode | OverpassElementWay;

export interface OverpassResponse {
  elements: OverpassElement[];
}

@Injectable({
  providedIn: 'root',
})
export class Overpass {
  private readonly apiUrl = 'https://overpass-api.de/api/interpreter';

  constructor(private http: HttpClient) {}

  fetchIndoorData(building_name: string) {
    const header = { 'Content-Type': 'text/plain' };
    const query = `
      [out:json][timeout:90];
      nwr["building"]["operator"="Hochschule Karlsruhe"]["name"="${building_name}"](49.014442, 8.387954, 49.017847, 8.395448)->.building;
      (
        nwr["indoor"="room"](area.building);
      );
      (._;>;);
      out body;
    `;

    return this.http.post<OverpassResponse>(this.apiUrl, query, { headers: header });
  }

  fetchBuildingData() {
    const header = { 'Content-Type': 'text/plain' };
    const query = `
      [out:json][timeout:90];
      (
        nwr["building"="university"]["operator"="Hochschule Karlsruhe"](49.014442, 8.387954, 49.017847, 8.395448);
      );
      (._;>;);
      out body;
    `;
    return this.http.post<OverpassResponse>(this.apiUrl, query, { headers: header });
  }
}
