import type { ApiService, ApiServiceCredentials } from "@/types";
import { axios, handleApiError } from "..";

export interface FetchApiServicesResponse {
  items: ApiService[];
  count: number;
}

export const getApiServices = async (): Promise<FetchApiServicesResponse> => {
  const response = await axios.get<FetchApiServicesResponse>(
    "/api/v1/admin/api-services",
  );

  if (response.status !== 200 && response.status !== 201)
    throw await handleApiError(response);

  return response.data;
};

export interface CreateApiServiceRequest {
  name: string;
  description: string;
  redirect_uris: string[];
  scopes: string[];
  grant_types: string[];
  is_active: boolean;
}

export interface CreateApiServiceResponse {
  service: ApiService;
  credentials: ApiServiceCredentials;
}

export const postApiService = async (
  req: CreateApiServiceRequest,
): Promise<CreateApiServiceResponse> => {
  const response = await axios.post<CreateApiServiceResponse>(
    "/api/v1/admin/api-services",
    req,
  );

  if (response.status !== 200 && response.status !== 201)
    throw await handleApiError(response);

  return response.data;
};

export const getApiService = async (id: string): Promise<ApiService> => {
  const response = await axios.get<ApiService>(
    `/api/v1/admin/api-services/${id}`,
  );

  if (response.status !== 200 && response.status !== 201)
    throw await handleApiError(response);

  return response.data;
};

export const patchToggleApiService = async (id: string): Promise<void> => {
  const response = await axios.patch(`/api/v1/admin/api-services/toggle/${id}`);

  if (response.status !== 200 && response.status !== 201)
    throw await handleApiError(response);

  return response.data;
};

export interface UpdateApiServiceRequest {
  name: string;
  description: string;
  redirect_uris: string[];
  scopes: string[];
  grant_types: string[];
}

export type UpdateApiServiceResponse = ApiService;

export const putApiService = async (
  serviceId: string,
  req: UpdateApiServiceRequest,
): Promise<UpdateApiServiceResponse> => {
  const response = await axios.put<UpdateApiServiceResponse>(
    `/api/v1/admin/api-services/${serviceId}`,
    req,
  );

  if (response.status !== 200 && response.status !== 201)
    throw await handleApiError(response);

  return response.data;
};
