import * as qs from "qs-esm";
import { ViewpointApiClient } from "../core";
import type { DestinationUnit } from "../type";

export class ViewpointDestination {
  private client: <TResponse>(
    path: string,
    init?: RequestInit,
  ) => Promise<TResponse | null>;
  constructor() {
    const baseURL = process.env.VIEWPOINT_API!;
    const token = process.env.VIEWPOINT_API_KEY!;

    if (!baseURL || !token) {
      throw new Error("Missing API or API Token");
    }
    this.client = ViewpointApiClient(baseURL, token);
  }
  /**
   * Finds available destination units by destinationCode and startDate(optional)
   * @param destinationCode {string} - destinationCode of the Destination
   * @param startDate {string} - Check in date. Example  `2025-07-22`
   * @param endDate {string} - Check out data [optional]. Example `2025-07-22`
   * @returns units {Unit[]}
   */
  async findDestinationUnit(
    destinationCode: string,
    startDate: string,
    endDate?: string,
  ): Promise<DestinationUnit[]> {
    try {
      const query: Record<string, string> = {};
      if (endDate) {
        query.endDate = endDate;
      }
      const queryStr = qs.stringify(query);
      const response = await this.client<DestinationUnit[]>(
        `/Availability/categorycounts/${destinationCode}/${startDate}?${queryStr}`,
        {
          method: "GET",
        },
      );

      if (!response) {
        return [];
      }

      return response;
    } catch (err) {
      console.log(err);
      return [];
    }
  }
}
