import axios from "axios";
import { ActivityRouteEntity } from "../../../../activity/domain/entities/activity_info_entity";
import { API_URL } from "../../../../common/const/api";
import { activityRouteModelToActivityRouteEntity } from "../../utils/route_utils";
import { RouteDataSource } from "../../../domain/datasource/route_datasource";
import { ActivityRouteModel } from "../../model/route_activity_model";
import { RouteEntity } from "../../../domain/entities/route";
import { RouteModel } from "../../model/route_model";

export class RouteDatasourceProd implements RouteDataSource {
  private readonly language: string;
  constructor(language: string) {
    this.language = language;
  }
  async saveRoute(id: number): Promise<void> {
    const { status } = await axios.patch(`${API_URL}/route/${id}`, {
      status: "accepted",
    });
    if (status !== 200) {
      throw new Error("Error saving route");
    }
  }
  async generateRoute(
    townId: number,
    startTime: number,
    endTime: number
  ): Promise<number> {
    const { data, status } = await axios.post<{ idRoute: number }>(
      `${API_URL}/route/${townId}?lang=${this.language}`,
      {
        start: startTime,
        end: endTime,
      }
    );
    console.info("Data loaded: ", data);
    if (status !== 201) {
      throw new Error("Error fetching route");
    }

    return data.idRoute;
  }
  async getRoute(routeId: number): Promise<RouteEntity> {
    const { status, data } = await axios.get<RouteModel>(
      `${API_URL}/route/${routeId}/${this.language}`
    );
    if (status !== 200) {
      throw new Error("Error fetching route");
    }
    console.info(data);
    return {
      idRoute: data.idRoute,
      startDate: new Date(data.startDate),
      endDate: new Date(data.endDate),
      status: data.status,
      travelPlaces: data.travelPlace.map((travelPlace) => {
        return {
          id: travelPlace.travelPlaceId,
          name: travelPlace.place.name,
          townId: data.town.townId,
          imageUri: travelPlace.place.imageName,
          location: travelPlace.place.address,
          coordinates: {
            latitude: +travelPlace.place.latitude,
            longitude: +travelPlace.place.longitude,
          },
          tags: travelPlace.place.categories.map((category) => category.name),
          startTime: new Date(travelPlace.startDate),
          endTime: new Date(travelPlace.endDate),
          done: travelPlace.done,
        };
      }),
    };
  }
}

// /state/state_id/town/town_id/activity/activity_id/travel?id=id_point_of_interest
