import { request } from "./core";

// ── Types ────────────────────────────────────────────────────────────────────

export interface LDAPGroupMapping {
  group_dn: string;
  role: string;
}

export interface LDAPConfig {
  id?: number;
  enabled: boolean;
  url: string;
  bind_dn: string;
  bind_password: string;
  base_dn: string;
  user_filter: string;
  tls: boolean;
  tls_skip_verify: boolean;
  default_role: string;
  group_mappings: LDAPGroupMapping[];
  updated_at?: string;
  updated_by?: string;
}

export interface LDAPTestUser {
  dn: string;
  uid: string;
  display_name: string;
  mail: string;
}

export interface LDAPFilterSuggestion {
  label: string;
  filter: string;
  description: string;
}

export interface LDAPTestResult {
  ok: boolean;
  message: string;
  latency_ms: number;
  server_info: string;
  users_found: number;
  users: LDAPTestUser[];
  object_classes: string[];
  filter_suggestions: LDAPFilterSuggestion[];
  error_detail: string;
}

// ── Global LDAP (superadmin) ──────────────────────────────────────────────────

export async function getLDAPConfig(): Promise<LDAPConfig | null> {
  try {
    return await request<LDAPConfig>("/api/admin/ldap");
  } catch (e: unknown) {
    if (e instanceof Error && e.message.includes("404")) return null;
    if (e instanceof Error && e.message.includes("no ldap config")) return null;
    throw e;
  }
}

export async function saveLDAPConfig(cfg: Partial<LDAPConfig>): Promise<void> {
  await request<void>("/api/admin/ldap", {
    method: "PUT",
    body: JSON.stringify(cfg),
  });
}

export async function deleteLDAPConfig(): Promise<void> {
  await request<void>("/api/admin/ldap", { method: "DELETE" });
}

export async function testLDAPConfig(
  payload: { use_saved: boolean } & Partial<LDAPConfig>
): Promise<LDAPTestResult> {
  return request<LDAPTestResult>("/api/admin/ldap/test", {
    method: "POST",
    body: JSON.stringify(payload),
  });
}
