import { createCoreAPIClient } from "@/lib/features/coreClient";
import { getAdminActivityLogs } from "@/lib/features/activity-logs/query";
import type { CoreResponse } from "@/lib/features/types";
import type { Resort, ResortListResponse } from "./types";

const coreClient = createCoreAPIClient();

export interface ListResortsParams {
  page?: number;
  limit?: number;
  search?: string;
  grade?: string;
  is_active?: string;
}

export async function listResorts(
  params?: ListResortsParams,
  headers?: HeadersInit,
): Promise<CoreResponse<ResortListResponse>> {
  const qs = new URLSearchParams();
  if (params?.page) qs.set("page", String(params.page));
  if (params?.limit) qs.set("limit", String(params.limit));
  if (params?.search) qs.set("search", params.search);
  if (params?.grade) qs.set("grade", params.grade);
  if (params?.is_active !== undefined) qs.set("is_active", params.is_active);
  const query = qs.toString();
  return coreClient<ResortListResponse>(
    `/v1/admin-console/resorts${query ? `?${query}` : ""}`,
    {
      method: "GET",
      headers,
    },
  );
}

export async function getResort(
  id: string,
  headers?: HeadersInit,
): Promise<CoreResponse<Resort>> {
  return coreClient<Resort>(`/v1/admin-console/resorts/${id}`, {
    method: "GET",
    headers,
  });
}

export async function getResortUnitTypes(
  headers?: HeadersInit,
): Promise<CoreResponse<string[]>> {
  return coreClient<string[]>("/v1/admin-console/resorts/meta/unit-types", {
    method: "GET",
    headers,
  });
}

export async function getEligibleUnits(
  resortId: string,
  offerType: string,
  headers?: HeadersInit,
): Promise<CoreResponse<any[]>> {
  return coreClient<any[]>(
    `/v1/admin-console/resorts/${resortId}/units/eligible?offerType=${offerType}`,
    { method: "GET", headers },
  );
}

export async function getResortLogs(
  resortId: string | null,
  page: number,
  pageSize: number,
) {
  const search = resortId
    ? `admin-console/resorts/${resortId}`
    : "admin-console/resorts";
  return getAdminActivityLogs(
    {
      search,
      method: ["POST", "PUT", "PATCH", "DELETE"],
      page,
      pageSize,
    },
    new Request(
      typeof window !== "undefined" ? window.location.href : "http://localhost",
    ),
  );
}
