import { IdentityProvider_Type, type IdentityProvider } from "@/types/proto/api/v1/idp_service_pb";
import { fetchJson, parseResourceId } from "./apiClient";
import { identityProviderFromApi } from "./converters";
import type { ApiIdentityProvider } from "./types";

export const identityProviderServiceClient = {
  async listIdentityProviders(_request?: unknown): Promise<{ identityProviders: IdentityProvider[] }> {
    void _request;
    const data = await fetchJson<ApiIdentityProvider[]>("/idp", { method: "GET" });
    const identityProviders = Array.isArray(data) ? data.map(identityProviderFromApi) : [];
    return { identityProviders };
  },
  async createIdentityProvider(request: { identityProvider?: IdentityProvider }): Promise<IdentityProvider> {
    const identityProvider = request.identityProvider;
    if (!identityProvider) {
      throw new Error("Missing identity provider payload");
    }
    const payload = {
      name: identityProvider.title || identityProvider.name || "identity-provider",
      type: identityProvider.type === IdentityProvider_Type.OAUTH2 ? "oauth2" : "unspecified",
    };
    const data = await fetchJson<ApiIdentityProvider>("/idp", { method: "POST", body: payload });
    return identityProviderFromApi(data);
  },
  async updateIdentityProvider(request: { identityProvider?: IdentityProvider }): Promise<IdentityProvider> {
    const identityProvider = request.identityProvider;
    if (!identityProvider?.name) {
      throw new Error("Missing identity provider name");
    }
    const idpId = parseResourceId(identityProvider.name);
    const payload = {
      name: identityProvider.title || identityProvider.name,
      config: identityProvider.config,
    };
    const data = await fetchJson<ApiIdentityProvider>(`/idp/${idpId}`, { method: "PATCH", body: payload });
    return identityProviderFromApi(data);
  },
  async deleteIdentityProvider(_request: { name: string }): Promise<void> {
    void _request;
    return;
  },
};

