import { CMSApiClient } from "../client";
import { CMSResortType } from "../types";
import { CMSCollectionMeta } from "../types/shared";

export class CMSResort {
  private client: <TResponse>(
    path: string,
    init?: RequestInit,
    params?: Record<string, unknown>,
  ) => Promise<TResponse | null>;
  constructor(private headers?: RequestInit["headers"]) {
    const baseURL = process.env.STRAPI_API as string;
    const token = process.env.STRAPI_API_KEY as string;

    if (!baseURL || !token) {
      throw new Error("Missing API or API Token");
    }
    this.client = CMSApiClient(baseURL, token);
  }

  // Retrieve resort by slug
  async findBySlug(slug: string) {
    try {
      const response = await this.client<CMSResortType>(
        `/destination-v2/${slug}`,
        {
          method: "GET",
          headers: this.headers,
        },
      );
      if (!response) {
        return [];
      }
      return response;
    } catch (err) {
      throw err instanceof Error ? err : new Error(String(err));
    }
  }

  // Retrieve all resorts
  async findAll(
    params?:
      | {
          filters?: Record<string, unknown> | undefined;
          populate?: Record<string, unknown> | undefined;
          pagination?: {
            type: "offset" | "page";
            start?: number;
            page?: number;
            limit?: number;
            pageSize?: number;
          };
        }
      | undefined,
  ): Promise<{
    data: CMSResortType[];
    meta: CMSCollectionMeta | undefined;
  } | null> {
    try {
      const response = await this.client<{
        data: CMSResortType[];
        meta: CMSCollectionMeta;
      }>(
        `/destinations`,
        {
          method: "GET",
          headers: this.headers,
        },
        params,
      );
      if (!response) {
        return {
          data: [],
          meta: undefined,
        };
      }
      return response;
    } catch (err) {
      throw err instanceof Error ? err : new Error(String(err));
    }
  }
}
