import type { ApiSettings, CredentialEnvelopeSummary, MailProfileScope } from "../types";
import { apiFetch } from "./client";

export type CredentialEnvelopePayload = {
  scope_type: MailProfileScope;
  scope_id?: string | null;
  name: string;
  description?: string | null;
  credential_kind: string;
  public_data?: Record<string, unknown>;
  secret_data?: Record<string, string>;
  allowed_modules?: string[];
  allowed_server_refs?: string[];
  inherit_to_lower_scopes?: boolean;
  is_active?: boolean;
};

export type CredentialEnvelopeUpdatePayload = Partial<
  Omit<CredentialEnvelopePayload, "scope_type" | "scope_id">
> & {
  clear_secret?: boolean;
};

export async function listCredentialEnvelopes(
  settings: ApiSettings,
  params: {
    scope_type: MailProfileScope;
    scope_id?: string | null;
    include_inactive?: boolean;
  }
): Promise<CredentialEnvelopeSummary[]> {
  const search = new URLSearchParams({ scope_type: params.scope_type });
  if (params.scope_id) search.set("scope_id", params.scope_id);
  if (params.include_inactive) search.set("include_inactive", "true");
  const response = await apiFetch<{ credentials: CredentialEnvelopeSummary[] }>(
    settings,
    `/api/v1/credentials?${search.toString()}`
  );
  return response.credentials;
}

export function createCredentialEnvelope(
  settings: ApiSettings,
  payload: CredentialEnvelopePayload
): Promise<CredentialEnvelopeSummary> {
  return apiFetch<CredentialEnvelopeSummary>(settings, "/api/v1/credentials", {
    method: "POST",
    body: JSON.stringify(payload)
  });
}

export function updateCredentialEnvelope(
  settings: ApiSettings,
  credentialId: string,
  payload: CredentialEnvelopeUpdatePayload
): Promise<CredentialEnvelopeSummary> {
  return apiFetch<CredentialEnvelopeSummary>(
    settings,
    `/api/v1/credentials/${encodeURIComponent(credentialId)}`,
    {
      method: "PATCH",
      body: JSON.stringify(payload)
    }
  );
}

export function deleteCredentialEnvelope(
  settings: ApiSettings,
  credentialId: string
): Promise<CredentialEnvelopeSummary> {
  return apiFetch<CredentialEnvelopeSummary>(
    settings,
    `/api/v1/credentials/${encodeURIComponent(credentialId)}`,
    { method: "DELETE" }
  );
}
