import axios from "axios";
import { StateDataSource } from "../../../domain/datasources/state_datasource";
import { StateEntity } from "../../../domain/entities/state_entity";
import { TownEntity } from "../../../domain/entities/town_entity";
import { StateModel } from "../../models/states_model";
import { stateModelToEntity } from "../../utils/states_utils";
import { TownModel } from "../../models/town_model";
import { townModelToEntity } from "../../utils/town_utils";
import { placeModelToEntity } from "../../utils/place_utils";
import { ActivityInfoEntity } from "../../../../activity/domain/entities/activity_info_entity";
import { ActivityModel } from "../../../../activity/infrastructure/models/activity_model";
import { API_URL } from "../../../../common/const/api";

export class StateDataSourceProd implements StateDataSource {
  private lang: string;
  constructor(lang: string = "es") {
    this.lang = lang;
  }
  async getStates(): Promise<StateEntity[]> {
    const { status, data } = await axios.get<StateModel[]>(API_URL + "/state");
    if (status !== 200) {
      throw new Error("Error fetching states");
    }
    return data.map(stateModelToEntity);
  }
  async getTowns(stateId: number): Promise<TownEntity[]> {
    const { status, data } = await axios.get<TownModel[]>(
      `${API_URL}/state/${stateId}/town?lang=${this.lang}`
    );
    if (status !== 200) {
      throw new Error("Error fetching towns");
    }
    return data.map(townModelToEntity);
  }
  async getTownActivities(townId: number): Promise<ActivityInfoEntity[]> {
    const { status, data } = await axios.get<ActivityModel[]>(
      `${API_URL}/place/town/${townId}/place?lang=${this.lang}`
    );
    if (status !== 200) {
      throw new Error("Error fetching activities");
    }
    console.log("data", data);
    return data.map(placeModelToEntity);
  }
  async getActivityInfo(
    activityId: number
  ): Promise<ActivityInfoEntity | undefined> {
    // TODO: get lang from user preferences
    // TODO: get townId from user preferences
    const { status, data } = await axios.get<ActivityModel>(
      `${API_URL}/place/${activityId}?lang=${this.lang}`
    );
    if (status !== 200) {
      throw new Error("Error fetching activity");
    }
    return placeModelToEntity(data);
  }
}
