import { del, get, patch, post } from "@/lib/api-client";

import {
  ApiKeyCreateRequestSchema,
  ApiKeyCreateResponseSchema,
  ApiKeyListSchema,
  ApiKeySchema,
  ApiKeyUpdateRequestSchema,
} from "@/features/api-keys/schemas";
import { ApiKeyTrendsResponseSchema, ApiKeyUsage7DayResponseSchema } from "@/features/apis/schemas";

const API_KEYS_BASE_PATH = "/api/api-keys";

export function listApiKeys() {
  return get(`${API_KEYS_BASE_PATH}/`, ApiKeyListSchema);
}

export function createApiKey(payload: unknown) {
  const validated = ApiKeyCreateRequestSchema.parse(payload);
  return post(`${API_KEYS_BASE_PATH}/`, ApiKeyCreateResponseSchema, {
    body: validated,
  });
}

export function updateApiKey(keyId: string, payload: unknown) {
  const validated = ApiKeyUpdateRequestSchema.parse(payload);
  return patch(`${API_KEYS_BASE_PATH}/${encodeURIComponent(keyId)}`, ApiKeySchema, {
    body: validated,
  });
}

export function deleteApiKey(keyId: string) {
  return del(`${API_KEYS_BASE_PATH}/${encodeURIComponent(keyId)}`);
}

export function regenerateApiKey(keyId: string) {
  return post(
    `${API_KEYS_BASE_PATH}/${encodeURIComponent(keyId)}/regenerate`,
    ApiKeyCreateResponseSchema,
  );
}

export function getApiKeyTrends(keyId: string) {
  return get(
    `${API_KEYS_BASE_PATH}/${encodeURIComponent(keyId)}/trends`,
    ApiKeyTrendsResponseSchema,
  );
}

export function getApiKeyUsage7Day(keyId: string) {
  return get(
    `${API_KEYS_BASE_PATH}/${encodeURIComponent(keyId)}/usage-7d`,
    ApiKeyUsage7DayResponseSchema,
  );
}
