import axios from "axios";
import { TravelDataSource } from "../../../domain/datasources/travel_datasource";
import { TravelDetails } from "../../../domain/entities/travel_details";
import { Route, TravelHistory } from "../../../domain/entities/travel_history";
import { API_URL } from "../../../../common/const/api";
import { TravelDatasourceDev } from "../dev/travel_datasource";
import { RouteModel } from "../../../../route/infrastructure/model/route_model";

export class TravelDatasourceProd implements TravelDataSource {
  async getTravelHistory(): Promise<TravelHistory> {
    const { data, status } = await axios.get<RouteModel[]>(
      `${API_URL}/route?routeStatus=accepted`
    );

    const activeTravels: Route[] = [];
    const pastTravels: Route[] = [];

    for (const route of data) {
      const date = new Date(route.endDate);
      if (date > new Date()) {
        activeTravels.push({
          id: route.idRoute,
          destination: route.town.name,
          startDate: new Date(route.startDate),
          endDate: new Date(route.endDate),
        });
      } else {
        pastTravels.push({
          id: route.idRoute,
          destination: route.town.name,
          startDate: new Date(route.startDate),
          endDate: new Date(route.endDate),
        });
      }
    }

    return {
      activeTravel: activeTravels.length > 0 ? activeTravels : undefined,
      pastTravels,
    };
  }
  async getTravelDetails(id: number): Promise<TravelDetails> {
    const { data, status } = await axios.get<RouteModel>(
      `${API_URL}/route/${id}/es`
    );
    if (status !== 200) {
      throw new Error("Error fetching travel details");
    }
    console.log(data);
    return {
      travel: {
        id: data.idRoute,
        imageUri: "http://192.168.0.14:3005/" + data.town.imageName,
        destination: data.town.name,
        startDate: new Date(data.startDate),
        endDate: new Date(data.endDate),
      },
      activityList: data.travelPlace.map((place) => ({
        id: place.place.idPlace,
        name: place.place.name,
        rating: place.place.idPlace < 5 ? 5 : 0,
        startDate: new Date(place.startDate),
        endDate: new Date(place.endDate),
        image: place.place.imageName,
      })),
    };
  }
  async getVisitImage(id: number): Promise<string> {
    const { data, status } = await axios.get<string>(
      `${API_URL}/visited/getImage/${id}`
    );
    if (status !== 200) {
      throw new Error("Error generating ");
    }

    return data;
  }
}
