import type { AppConfig, AuthSession, BillingEvent, BillingProviderInfo, CalendarEvent, CalendarReminderNotification, CalendarSource, CalendarStatus, Contact, ContactFolder, DistributionList, Domain, DriveFile, DriveStatus, Folder, FolderShare, GoogleTask, GoogleTaskList, InvoiceRecord, LoginResponse, MailFilterRule, MailImportResult, MailLimits, MailMigrationConnectionResult, MailMigrationJob, MailQuota, MailSignature, Mailbox, MailboxProfile, MessageDetail, MessagePage, MessageSummary, NativeZimbraShareEntry, NativeZimbraTask, NativeZimbraTaskList, Organization, OutOfOfficePreferences, ProvisioningSummary, SavedSearch, ShareNotification, Subscription, Tag, TenantAdminLoginResponse, TwoFactorRecoveryCodes, TwoFactorStatus, WorkspaceFilters, WorkspacePreferences } from "./types";
import { DEFAULT_TIME_ZONE } from "./time-zone";

const DEFAULT_API_PREFIX = process.env.NEXT_PUBLIC_API_PREFIX || "/api";
let tenantAdminMailboxEmail = "";

export function setTenantAdminMailboxEmail(email: string) {
  tenantAdminMailboxEmail = email.trim().toLowerCase();
}

function tenantAdminHeaders(adminToken: string) {
  const headers: Record<string, string> = { "X-Admin-Token": adminToken };
  if (tenantAdminMailboxEmail) {
    headers["X-Admin-Mailbox"] = tenantAdminMailboxEmail;
  }
  return headers;
}

function getApiPrefix() {
  if (typeof window !== "undefined") {
    const pathname = window.location.pathname;
    if (pathname === "/admin" || pathname.startsWith("/admin/")) {
      return "/api/admin";
    }
  }
  return DEFAULT_API_PREFIX;
}

async function request<T>(path: string, init?: RequestInit, apiPrefix = getApiPrefix()): Promise<T> {
  const response = await fetch(`${apiPrefix}${path}`, {
    ...init,
    cache: "no-store",
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
      ...(init?.headers ?? {})
    }
  });
  const contentType = response.headers.get("content-type") || "";
  let data: Record<string, unknown> = {};
  let fallbackText = "";
  if (contentType.includes("application/json")) {
    data = await response.json().catch(() => ({}));
  } else {
    fallbackText = sanitizeErrorText(await response.text().catch(() => ""));
  }
  if (!response.ok) {
    const validationMessage = Array.isArray(data.detail)
      ? data.detail
          .map((item) => {
            if (!item || typeof item !== "object") return "";
            const loc = Array.isArray(item.loc) ? item.loc.join(".") : "";
            const msg = typeof item.msg === "string" ? item.msg : "";
            return [loc, msg].filter(Boolean).join(": ");
          })
          .filter(Boolean)
          .join(" | ")
      : "";
    const message =
      validationMessage ||
      (typeof data.detail === "string" && data.detail) ||
      (typeof data.error === "string" && data.error) ||
      fallbackText;
    if ((path.startsWith("/auth/login") || path === "/admin/login") && (response.status === 401 || response.status === 502 || response.status === 503) && isGatewayLikeError(message)) {
      throw new Error("Invalid email or password");
    }
    if ((path.startsWith("/auth/login") || path === "/admin/login") && response.status === 401 && !message) {
      throw new Error("Invalid email or password");
    }
    if ((path === "/mail/send" || path === "/mail/drafts" || path === "/mail/calendar/invites/respond") && response.status === 413) {
      throw new Error("The mail server rejected this message or attachment. Remove attachments or send smaller files.");
    }
    if (path.startsWith("/admin/distribution-lists/") && init?.method === "DELETE" && (response.status === 502 || response.status === 503 || response.status === 504) && isGatewayLikeError(message)) {
      if (path.includes("/members/")) {
        throw new Error("Distribution list member could not be removed");
      }
      throw new Error("Distribution list could not be deleted");
    }
    throw new Error(message || `Request failed (${response.status})`);
  }
  return data as T;
}

function sanitizeErrorText(value: string) {
  const stripped = value
    .replace(/<script[\s\S]*?<\/script>/gi, " ")
    .replace(/<style[\s\S]*?<\/style>/gi, " ")
    .replace(/<\/?[^>]+>/g, " ")
    .replace(/\s+/g, " ")
    .trim();
  if (!stripped) {
    return "";
  }
  return stripped.length > 180 ? `${stripped.slice(0, 177)}...` : stripped;
}

function isGatewayLikeError(value: string) {
  const text = value.toLowerCase();
  return text.includes("cloudflare") || text.includes("bad gateway") || text.includes("502") || text.includes("error code 502");
}

async function requestText(path: string, init?: RequestInit): Promise<string> {
  const response = await fetch(`${getApiPrefix()}${path}`, {
    ...init,
    cache: "no-store",
    credentials: "include",
    headers: {
      ...(init?.headers ?? {})
    }
  });
  const text = await response.text().catch(() => "");
  if (!response.ok) {
    throw new Error(text.trim() || `Request failed (${response.status})`);
  }
  return text;
}

async function requestBlob(path: string, init?: RequestInit): Promise<Blob> {
  const response = await fetch(`${getApiPrefix()}${path}`, {
    ...init,
    cache: "no-store",
    credentials: "include",
    headers: {
      ...(init?.headers ?? {})
    }
  });
  if (!response.ok) {
    const text = await response.text().catch(() => "");
    throw new Error(text.trim() || `Request failed (${response.status})`);
  }
  return response.blob();
}

async function requestFormData<T>(path: string, body: FormData, init?: RequestInit): Promise<T> {
  const response = await fetch(`${getApiPrefix()}${path}`, {
    ...init,
    method: init?.method || "POST",
    body,
    cache: "no-store",
    credentials: "include",
    headers: {
      ...(init?.headers ?? {})
    }
  });
  const contentType = response.headers.get("content-type") || "";
  const data = contentType.includes("application/json") ? await response.json().catch(() => ({})) : {};
  if (!response.ok) {
    const detail = typeof (data as Record<string, unknown>).detail === "string" ? String((data as Record<string, unknown>).detail) : "";
    throw new Error(detail || `Request failed (${response.status})`);
  }
  return data as T;
}

function requestFormDataWithProgress<T>(
  path: string,
  body: FormData,
  onProgress?: (loaded: number, total: number) => void,
): Promise<T> {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("POST", `${getApiPrefix()}${path}`);
    xhr.withCredentials = true;
    xhr.responseType = "text";
    xhr.upload.onprogress = (event) => {
      if (event.lengthComputable) {
        onProgress?.(event.loaded, event.total);
      }
    };
    xhr.onload = () => {
      const contentType = xhr.getResponseHeader("content-type") || "";
      const text = xhr.responseText || "";
      if (xhr.status < 200 || xhr.status >= 300) {
        const data = contentType.includes("application/json") ? safeJsonParse(text) : {};
        const detail = typeof data.detail === "string" ? data.detail : text.trim();
        reject(new Error(detail || `Request failed (${xhr.status})`));
        return;
      }
      try {
        resolve((contentType.includes("application/json") ? JSON.parse(text || "{}") : {}) as T);
      } catch {
        reject(new Error("Invalid JSON response"));
      }
    };
    xhr.onerror = () => reject(new Error("Network error"));
    xhr.send(body);
  });
}

function safeJsonParse(value: string) {
  try {
    return JSON.parse(value || "{}");
  } catch {
    return {};
  }
}

export const api = {
  config: (domain = "") => request<AppConfig>(`/config${domain ? `?domain=${encodeURIComponent(domain)}` : ""}`, undefined, "/api"),
  branding: (domain = "") => request<{ branding: AppConfig["branding"] }>(`/branding${domain ? `?domain=${encodeURIComponent(domain)}` : ""}`, undefined, "/api"),
  billingProviders: () => request<{ providers: BillingProviderInfo[] }>("/billing/providers"),
  billingProvider: (providerName: string) => request<BillingProviderInfo>(`/billing/providers/${encodeURIComponent(providerName)}`),
  me: () => request<AuthSession>("/auth/me"),
  keepAlive: () => request<AuthSession>("/auth/keepalive", { method: "POST" }),
  workspacePreferences: () => request<WorkspacePreferences>("/auth/preferences"),
  mailPollingInterval: () => request<{ interval_seconds: number; interval_ms: number; source: string }>("/auth/mail-polling-interval"),
  updateWorkspacePreferences: (payload: {
    drive_save_folder_id: string;
    drive_save_folder_name: string;
    message_view_mode?: "conversation" | "message";
    theme?: string;
    font_scale?: string;
    time_zone?: string;
    locale?: string;
  }) =>
    request<WorkspacePreferences>("/auth/preferences", {
      method: "PATCH",
      body: JSON.stringify(payload)
    }),
  outOfOfficePreferences: () => request<OutOfOfficePreferences>("/auth/out-of-office"),
  updateOutOfOfficePreferences: (payload: {
    enabled: boolean;
    reply_mode: "off" | "reply";
    use_time_period: boolean;
    start_date: string;
    end_date: string;
    subject: string;
    message: string;
  }) =>
    request<OutOfOfficePreferences>("/auth/out-of-office", {
      method: "PATCH",
      body: JSON.stringify(payload)
    }),
  workspaceFilters: () => request<WorkspaceFilters>("/auth/filters"),
  updateWorkspaceFilters: (payload: { rules: MailFilterRule[] }) =>
    request<WorkspaceFilters>("/auth/filters", {
      method: "PATCH",
      body: JSON.stringify(payload)
    }),
  testMailMigrationConnection: (payload: {
    source_host: string;
    source_port: number;
    source_security: "ssl" | "starttls" | "plain";
    source_skip_ssl_verify?: boolean;
    source_username: string;
    source_password: string;
  }) =>
    request<MailMigrationConnectionResult>("/mail/migrations/test-connection", {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  startMailImportUpload: (payload: { filename: string; folder: string }) =>
    request<{ upload_id: string; filename: string; folder: string }>("/mail/import/uploads", {
      method: "POST",
      body: JSON.stringify(payload),
    }),
  uploadMailImportChunk: (uploadId: string, chunk: Blob) =>
    request<{ upload_id: string; bytes: number }>(`/mail/import/uploads/${encodeURIComponent(uploadId)}`, {
      method: "POST",
      body: chunk,
      headers: {
        "Content-Type": "application/octet-stream",
      },
    }),
  finishMailImportUpload: (uploadId: string) =>
    request<{ job: { id: string; status: string; phase: string } }>(`/mail/import/uploads/${encodeURIComponent(uploadId)}/finish`, {
      method: "POST",
    }),
  cancelMailImportUpload: (uploadId: string) =>
    request<{ ok: boolean }>(`/mail/import/uploads/${encodeURIComponent(uploadId)}/cancel`, {
      method: "POST",
    }),
  mailMigrations: () => request<{ jobs: MailMigrationJob[] }>("/mail/migrations"),
  clearMailMigrations: () => request<{ ok: boolean; cleared: boolean; active_jobs: number }>("/mail/migrations", { method: "DELETE" }),
  mailMigration: (jobId: string) => request<{ job: MailMigrationJob }>(`/mail/migrations/${encodeURIComponent(jobId)}`),
  startMailMigration: (payload: {
    label?: string;
    source_host: string;
    source_port: number;
    source_security: "ssl" | "starttls" | "plain";
    source_skip_ssl_verify?: boolean;
    source_username: string;
    source_password: string;
    dry_run?: boolean;
    include_folders?: string[];
    exclude_folders?: string[];
  }) =>
    request<{ job: MailMigrationJob }>("/mail/migrations", {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  cancelMailMigration: (jobId: string) =>
    request<{ job: MailMigrationJob }>(`/mail/migrations/${encodeURIComponent(jobId)}/cancel`, {
      method: "POST"
    }),
  importMailArchive: (file: File, folder = "Inbox") => {
    const body = new FormData();
    body.append("file", file);
    body.append("folder", folder);
    return requestFormData<{ job: { id: string; status: string; phase: string } }>("/mail/import", body);
  },
  importMailArchiveWithProgress: (file: File, folder = "Inbox", onProgress?: (loaded: number, total: number) => void) => {
    const body = new FormData();
    body.append("file", file);
    body.append("folder", folder);
    return requestFormDataWithProgress<{ job: { id: string; status: string; phase: string } }>("/mail/import", body, onProgress);
  },
  getMailImportArchiveJob: (jobId: string) => request<{ job: { id: string; status: string; phase: string } }>(`/mail/import/jobs/${encodeURIComponent(jobId)}`),
  exportMailArchiveBlob: () => requestBlob("/mail/export/archive"),
  startMailExportArchiveJob: () => request<{ job: { id: string; status: string; phase: string } }>("/mail/export/archive/jobs", { method: "POST" }),
  getMailExportArchiveJob: (jobId: string) => request<{ job: { id: string; status: string; phase: string; result_filename?: string; result_media_type?: string } }>(`/mail/export/archive/jobs/${encodeURIComponent(jobId)}`),
  downloadMailExportArchiveJob: (jobId: string) => requestBlob(`/mail/export/archive/jobs/${encodeURIComponent(jobId)}/download`),
  login: (payload: Record<string, unknown>) => request<LoginResponse>("/auth/login", {
    method: "POST",
    body: JSON.stringify(payload)
  }),
  demoLogin: (google = false) => request<LoginResponse>(`/auth/demo${google ? "?google=true" : ""}`, { method: "POST" }),
  loginTwoFactor: (payload: { challenge_token: string; code: string }) =>
    request<LoginResponse>("/auth/login/2fa", {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  logout: () => request<{ ok: boolean }>("/auth/logout", { method: "POST" }),
  changePassword: (payload: { current_password: string; password: string }) => request<{ ok: boolean }>("/auth/password", {
    method: "PATCH",
    body: JSON.stringify(payload)
  }),
  accountProfile: () => request<MailboxProfile>("/auth/profile"),
  updateAccountProfile: (payload: Pick<MailboxProfile, "display_name" | "first_name" | "surname">) => request<MailboxProfile>("/auth/profile", {
    method: "PATCH",
    body: JSON.stringify(payload),
  }),
  uploadAccountProfilePhoto: (file: File) => {
    const body = new FormData();
    body.append("file", file);
    return requestFormData<{ photo_url: string }>("/auth/profile/photo", body, { method: "PUT" });
  },
  deleteAccountProfilePhoto: () => request<{ ok: boolean }>("/auth/profile/photo", { method: "DELETE" }),
  twoFactorStatus: () => request<TwoFactorStatus>("/auth/2fa/status"),
  twoFactorSetup: () => request<TwoFactorStatus>("/auth/2fa/setup", { method: "POST" }),
  twoFactorEnable: (payload: { code: string }) => request<TwoFactorStatus>("/auth/2fa/enable", {
    method: "POST",
    body: JSON.stringify(payload)
  }),
  twoFactorDisable: () => request<TwoFactorStatus>("/auth/2fa/disable", { method: "POST" }),
  twoFactorRecoveryCodes: () => request<TwoFactorRecoveryCodes>("/auth/2fa/recovery-codes", { method: "POST" }),
  contacts: (folderId = "") => request<{ contacts: Contact[] }>(`/contacts${folderId ? `?folder_id=${encodeURIComponent(folderId)}` : ""}`),
  galContacts: () => request<{ contacts: Contact[] }>("/contacts/gal"),
  contactFolders: () => request<{ folders: ContactFolder[] }>("/contacts/folders"),
  createContactFolder: (name: string) => request<{ folders: ContactFolder[] }>("/contacts/folders", {
    method: "POST",
    body: JSON.stringify({ name })
  }),
  renameContactFolder: (folderId: string, name: string) => request<{ folders: ContactFolder[] }>(`/contacts/folders/${encodeURIComponent(folderId)}`, {
    method: "PATCH",
    body: JSON.stringify({ name })
  }),
  updateContactFolderColor: (folderId: string, payload: { color: number; rgb?: string }) => request<{ folders: ContactFolder[] }>(`/contacts/folders/${encodeURIComponent(folderId)}/color`, {
    method: "PATCH",
    body: JSON.stringify(payload)
  }),
  deleteContactFolder: (folderId: string) => request<{ folders: ContactFolder[] }>(`/contacts/folders/${encodeURIComponent(folderId)}`, {
    method: "DELETE"
  }),
  contactFolderShares: (folderId: string) => request<{ shares: FolderShare[] }>(`/contacts/folders/${encodeURIComponent(folderId)}/shares`),
  shareContactFolder: (folderId: string, payload: { email: string; permissions: string }) =>
    request<{ folders: ContactFolder[] }>(`/contacts/folders/${encodeURIComponent(folderId)}/shares`, {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  revokeContactFolderShare: (folderId: string, payload: { email: string }) =>
    request<{ folders: ContactFolder[] }>(`/contacts/folders/${encodeURIComponent(folderId)}/shares`, {
      method: "DELETE",
      body: JSON.stringify(payload)
    }),
  createContact: (payload: {
    folder_id?: string;
    full_name?: string;
    first_name?: string;
    last_name?: string;
    email: string;
    company?: string;
    notes?: string;
    phone?: string;
  }) => request<{ contact: Contact }>("/contacts", {
    method: "POST",
    body: JSON.stringify(payload)
  }),
  updateContact: (contactId: string, payload: {
    full_name?: string;
    first_name?: string;
    last_name?: string;
    email: string;
    company?: string;
    notes?: string;
    phone?: string;
  }) => request<{ contact: Contact }>(`/contacts/${encodeURIComponent(contactId)}`, {
    method: "PATCH",
    body: JSON.stringify(payload)
  }),
  uploadContactPhoto: (contactId: string, file: File) => {
    const body = new FormData();
    body.append("file", file);
    return requestFormData<{ photo_url: string }>(`/contacts/${encodeURIComponent(contactId)}/photo`, body, { method: "PUT" });
  },
  deleteContactPhoto: (contactId: string) => request<{ ok: boolean }>(`/contacts/${encodeURIComponent(contactId)}/photo`, { method: "DELETE" }),
  deleteContact: (contactId: string) => request<{ ok: boolean }>(`/contacts/${encodeURIComponent(contactId)}`, {
    method: "DELETE"
  }),
  folders: (fresh = false) => request<{ folders: Folder[]; starred_unread_count: number }>(`/mail/folders${fresh ? "?fresh=true" : ""}`),
  tags: () => request<{ tags: Tag[] }>("/mail/tags"),
  createTag: (payload: { name: string; color: number }) => request<{ tags: Tag[] }>("/mail/tags", {
    method: "POST",
    body: JSON.stringify(payload)
  }),
  updateTag: (tagId: string, payload: { name?: string; color?: number }) => request<{ tags: Tag[] }>(`/mail/tags/${encodeURIComponent(tagId)}`, {
    method: "PATCH",
    body: JSON.stringify(payload)
  }),
  deleteTag: (tagId: string) => request<{ tags: Tag[] }>(`/mail/tags/${encodeURIComponent(tagId)}`, {
    method: "DELETE"
  }),
  createFolder: (name: string) => request<{ folders: Folder[]; starred_unread_count: number }>("/mail/folders", {
    method: "POST",
    body: JSON.stringify({ name })
  }),
  renameFolder: (folderId: string, name: string) => request<{ folders: Folder[]; starred_unread_count: number }>(`/mail/folders/${encodeURIComponent(folderId)}`, {
    method: "PATCH",
    body: JSON.stringify({ name })
  }),
  updateFolderColor: (folderId: string, payload: { color: number; rgb?: string }) => request<{ folders: Folder[]; starred_unread_count: number }>(`/mail/folders/${encodeURIComponent(folderId)}/color`, {
    method: "PATCH",
    body: JSON.stringify(payload)
  }),
  deleteFolder: (folderId: string) => request<{ folders: Folder[]; starred_unread_count: number }>(`/mail/folders/${encodeURIComponent(folderId)}`, {
    method: "DELETE"
  }),
  emptyFolder: (folderId: string) => request<{ folders: Folder[]; starred_unread_count: number }>(`/mail/folders/${encodeURIComponent(folderId)}/empty`, {
    method: "POST"
  }),
  shareFolder: (folderId: string, payload: { email: string; permissions: string }) =>
    request<{ folders: Folder[]; starred_unread_count: number }>(`/mail/folders/${encodeURIComponent(folderId)}/shares`, {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  revokeFolderShare: (folderId: string, payload: { email: string }) =>
    request<{ folders: Folder[]; starred_unread_count: number }>(`/mail/folders/${encodeURIComponent(folderId)}/shares`, {
      method: "DELETE",
      body: JSON.stringify(payload)
    }),
  shareNotifications: () => request<{ notifications: ShareNotification[] }>("/mail/shares/notifications"),
  acceptShareNotification: (notificationId: string) =>
    request<{ notification: ShareNotification; mountpoint: string }>(`/mail/shares/notifications/${encodeURIComponent(notificationId)}/accept`, {
      method: "POST"
  }),
  declineShareNotification: (notificationId: string) =>
    request<{ notification: ShareNotification }>(`/mail/shares/notifications/${encodeURIComponent(notificationId)}/decline`, {
      method: "POST"
  }),
  acceptShareInvite: (payload: { grantor_id?: string; grantor_email?: string; grantor_name?: string; item_id: string; item_name?: string; item_view?: string; item_perm?: string; mount_name?: string }) =>
    request<{ notification: ShareNotification; mountpoint: string }>("/mail/shares/invites/accept", {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  acceptMessageShareInvite: (uid: string, payload: { part: string; mount_name?: string }) =>
    request<{ notification: ShareNotification; mountpoint: string }>(`/mail/messages/${encodeURIComponent(uid)}/share-invite/accept`, {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  declineMessageShareInvite: (uid: string, payload: { part?: string }) =>
    request<{ notification: ShareNotification }>(`/mail/messages/${encodeURIComponent(uid)}/share-invite/decline`, {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  quota: (folder = "INBOX") => request<{ quota: MailQuota }>(`/mail/quota?folder=${encodeURIComponent(folder)}`),
  mailLimits: () => request<{ limits: MailLimits }>("/mail/limits"),
  signatures: () => request<{ signatures: MailSignature[]; default_signature: MailSignature | null; reply_signature: MailSignature | null }>("/mail/signatures"),
  updateSignatures: (payload: { content: string; content_html: string; content_type: string }) =>
    request<{ signatures: MailSignature[]; default_signature: MailSignature | null; reply_signature: MailSignature | null }>("/mail/signatures", {
      method: "PATCH",
      body: JSON.stringify(payload)
    }),
  messages: (folder: string, limit = 50, offset = 0, view: "conversation" | "message" = "conversation", sortOrder: "newest" | "oldest" = "newest") =>
    request<MessagePage>(`/mail/messages?folder=${encodeURIComponent(folder)}&limit=${encodeURIComponent(limit)}&offset=${encodeURIComponent(offset)}&view=${encodeURIComponent(view)}&sort_order=${encodeURIComponent(sortOrder)}`),
  searchAll: (q: string, folder = "") => request<{ messages: MessageSummary[] }>(`/mail/search?q=${encodeURIComponent(q)}${folder ? `&folder=${encodeURIComponent(folder)}` : ""}`),
  savedSearches: () => request<{ searches: SavedSearch[] }>("/mail/saved-searches"),
  createSavedSearch: (name: string, query: string) => request<{ search: SavedSearch }>("/mail/saved-searches", { method: "POST", body: JSON.stringify({ name, query }) }),
  updateSavedSearch: (id: string, name: string, query: string) => request<{ search: SavedSearch }>(`/mail/saved-searches/${encodeURIComponent(id)}`, { method: "PATCH", body: JSON.stringify({ name, query }) }),
  deleteSavedSearch: (id: string) => request<{ ok: boolean }>(`/mail/saved-searches/${encodeURIComponent(id)}`, { method: "DELETE" }),
  message: (folder: string, uid: string, view: "conversation" | "message" = "message") => request<{ message: MessageDetail }>(`/mail/messages/${uid}?folder=${encodeURIComponent(folder)}&view=${encodeURIComponent(view)}`),
  sendReadReceipt: (uid: string) => request<{ ok: boolean }>(`/mail/messages/${encodeURIComponent(uid)}/read-receipt`, { method: "POST" }),
  original: (uid: string) => requestText(`/mail/messages/${uid}/original`),
  originalBlob: (uid: string) => requestBlob(`/mail/messages/${encodeURIComponent(uid)}/original`),
  deleteMessage: (folder: string, uid: string, view: "conversation" | "message" = "message") => request<{ ok: boolean }>(`/mail/messages/${uid}?folder=${encodeURIComponent(folder)}&view=${encodeURIComponent(view)}`, {
    method: "DELETE"
  }),
  moveMessage: (folder: string, uid: string, target_folder: string, view: "conversation" | "message" = "message") => request<{ ok: boolean }>(`/mail/messages/${uid}/move?folder=${encodeURIComponent(folder)}&view=${encodeURIComponent(view)}`, {
    method: "PATCH",
    body: JSON.stringify({ target_folder })
  }),
  updateFlags: (folder: string, uid: string, payload: { seen?: boolean; starred?: boolean }, view: "conversation" | "message" = "message") => request<{ ok: boolean }>(`/mail/messages/${uid}/flags?folder=${encodeURIComponent(folder)}&view=${encodeURIComponent(view)}`, {
    method: "PATCH",
    body: JSON.stringify(payload)
  }),
  updateMessageTags: (folder: string, uid: string, payload: { add?: string[]; remove?: string[] }, view: "conversation" | "message" = "message") => request<{ ok: boolean; tags: string[] }>(`/mail/messages/${uid}/tags?folder=${encodeURIComponent(folder)}&view=${encodeURIComponent(view)}`, {
    method: "PATCH",
    body: JSON.stringify(payload)
  }),
  send: (payload: Record<string, unknown>) => request<{ ok: boolean; scheduled: boolean; send_at_ms?: number; draft_id?: string }>("/mail/send", {
    method: "POST",
    body: JSON.stringify(payload)
  }),
  respondCalendarInvite: (payload: {
    message: {
      folder: string;
      uid: string;
      open_uid?: string;
    };
    invite: {
      method: string;
      uid: string;
      summary: string;
      description: string;
      location: string;
      organizer: string;
      attendees: string[];
      start: string;
      end: string;
      all_day: boolean;
      reminder_minutes: number;
    };
    response: "accepted" | "tentative" | "declined";
  }) => request<{ ok: boolean }>("/mail/calendar/invites/respond", {
    method: "POST",
    body: JSON.stringify(payload),
  }),
  saveDraft: (payload: Record<string, unknown>) => request<{ ok: boolean; draft_id: string }>("/mail/drafts", {
    method: "POST",
    body: JSON.stringify(payload)
  }),
  calendarStatus: () => request<CalendarStatus>("/calendar/status"),
  calendarConnectUrl: () => request<{ url: string }>("/calendar/auth-url"),
  calendarResync: () => request<{ ok: boolean; status: string; watch_supported: boolean; watch_error: string; calendars: CalendarSource[] }>("/calendar/resync", { method: "POST" }),
  disconnectCalendar: () => request<{ ok: boolean }>("/calendar/connection", { method: "DELETE" }),
  calendars: () => request<{ calendars: CalendarSource[] }>("/calendar/calendars"),
  createCalendar: (name: string) =>
    request<{ calendars: CalendarSource[] }>("/calendar/calendars", {
      method: "POST",
      body: JSON.stringify({ name })
    }),
  renameCalendar: (calendarId: string, name: string) =>
    request<{ calendars: CalendarSource[] }>(`/calendar/calendars/${encodeURIComponent(calendarId)}`, {
      method: "PATCH",
      body: JSON.stringify({ name })
    }),
  deleteCalendar: (calendarId: string) =>
    request<{ calendars: CalendarSource[] }>(`/calendar/calendars/${encodeURIComponent(calendarId)}`, {
      method: "DELETE"
    }),
  updateCalendarColor: (calendarId: string, payload: { calendarId?: string; color: number; rgb?: string }) =>
    request<{ calendars: CalendarSource[] }>(`/calendar/calendars/${encodeURIComponent(calendarId)}/color`, {
      method: "PATCH",
      body: JSON.stringify(payload)
    }),
  calendarShares: () => request<{ shares: FolderShare[] }>("/calendar/shares"),
  nativeZimbraCalendarShares: (resourceId = "") => request<{ shares: NativeZimbraShareEntry[] }>(`/native-zimbra/shares/calendar${resourceId ? `?resource_id=${encodeURIComponent(resourceId)}` : ""}`),
  shareCalendar: (payload: { resource_id?: string; email: string; permissions: string }) =>
    request<{ shares: FolderShare[] }>("/calendar/shares", {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  nativeZimbraShareCalendar: (payload: { resource_id?: string; email: string; permissions: string }) =>
    request<{ shares: NativeZimbraShareEntry[] }>("/native-zimbra/shares/calendar", {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  revokeCalendarShare: (payload: { resource_id?: string; email: string }) =>
    request<{ shares: FolderShare[] }>("/calendar/shares", {
      method: "DELETE",
      body: JSON.stringify(payload)
    }),
  nativeZimbraRevokeCalendarShare: (payload: { resource_id?: string; email: string }) =>
    request<{ shares: NativeZimbraShareEntry[] }>("/native-zimbra/shares/calendar", {
      method: "DELETE",
      body: JSON.stringify(payload)
    }),
  nativeZimbraTaskShares: (resourceId = "") => request<{ shares: NativeZimbraShareEntry[] }>(`/native-zimbra/shares/tasks${resourceId ? `?resource_id=${encodeURIComponent(resourceId)}` : ""}`),
  nativeZimbraShareTask: (payload: { resource_id?: string; email: string; permissions: string }) =>
    request<{ shares: NativeZimbraShareEntry[] }>("/native-zimbra/shares/tasks", {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  nativeZimbraRevokeTaskShare: (payload: { resource_id?: string; email: string }) =>
    request<{ shares: NativeZimbraShareEntry[] }>("/native-zimbra/shares/tasks", {
      method: "DELETE",
      body: JSON.stringify(payload)
    }),
  googleTasksStatus: () => request<{ configured: boolean; oauth_configured: boolean; connected: boolean; writable: boolean; mode: "oauth" | "none" }>("/google/tasks/status"),
  googleTaskLists: () => request<{ lists: GoogleTaskList[] }>("/google/tasks/lists"),
  createGoogleTaskList: (payload: { title: string }) =>
    request<{ list: GoogleTaskList }>("/google/tasks/lists", {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  updateGoogleTaskListColor: (listId: string, payload: { color: number; rgb?: string }) =>
    request<{ list: GoogleTaskList }>(`/google/tasks/lists/${encodeURIComponent(listId)}/color`, {
      method: "PATCH",
      body: JSON.stringify(payload)
    }),
  googleTasks: (listId = "@default") => request<{ tasks: GoogleTask[] }>(`/google/tasks?list_id=${encodeURIComponent(listId || "@default")}`),
  createGoogleTask: (payload: { list_id: string; title: string; notes?: string; due?: string }) =>
    request<{ task: GoogleTask }>("/google/tasks", {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  updateGoogleTask: (taskId: string, payload: { list_id: string; title: string; notes?: string; due?: string; status?: string }) =>
    request<{ task: GoogleTask }>(`/google/tasks/${encodeURIComponent(taskId)}`, {
      method: "PATCH",
      body: JSON.stringify(payload)
    }),
  deleteGoogleTask: (taskId: string, listId = "@default") =>
    request<{ ok: boolean }>(`/google/tasks/${encodeURIComponent(taskId)}?list_id=${encodeURIComponent(listId || "@default")}`, {
      method: "DELETE"
    }),
  calendar: (calendarId = "primary", timeZone = DEFAULT_TIME_ZONE, timeMin?: string, timeMax?: string) =>
    request<{ events: CalendarEvent[] }>(
      `/calendar/events?calendar_id=${encodeURIComponent(calendarId)}&time_zone=${encodeURIComponent(timeZone)}${timeMin ? `&time_min=${encodeURIComponent(timeMin)}` : ""}${timeMax ? `&time_max=${encodeURIComponent(timeMax)}` : ""}`
    ),
  driveStatus: () => request<DriveStatus>("/drive/status"),
  driveAuthUrl: () => request<{ url: string }>("/drive/auth-url"),
  disconnectDrive: () => request<{ ok: boolean }>("/drive/connection", { method: "DELETE" }),
  driveFiles: (q = "", limit = 50) => request<{ files: DriveFile[] }>(`/drive/files?q=${encodeURIComponent(q)}&limit=${encodeURIComponent(limit)}`),
  driveContents: (folderId = "", q = "", limit = 50) =>
    request<{ folders: DriveFile[]; files: DriveFile[] }>(
      `/drive/contents?folder_id=${encodeURIComponent(folderId)}&q=${encodeURIComponent(q)}&limit=${encodeURIComponent(limit)}`
    ),
  driveFolders: (q = "", limit = 50) => request<{ folders: DriveFile[] }>(`/drive/folders?q=${encodeURIComponent(q)}&limit=${encodeURIComponent(limit)}`),
  driveCreateFolder: (payload: { name: string; parent_id?: string }) =>
    request<{ file: DriveFile }>("/drive/folders", {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  driveUpdateFolderColor: (folderId: string, payload: { color: number; rgb?: string }) =>
    request<{ file: DriveFile }>(`/drive/folders/${encodeURIComponent(folderId)}/color`, {
      method: "PATCH",
      body: JSON.stringify(payload)
    }),
  driveDownload: (fileId: string, preview = false) => requestBlob(`/drive/files/${encodeURIComponent(fileId)}/download${preview ? "?preview=1" : ""}`),
  driveFile: (fileId: string) => request<{ file: DriveFile }>(`/drive/files/${encodeURIComponent(fileId)}`),
  driveShareLink: (fileId: string) => request<{ file: DriveFile }>(`/drive/files/${encodeURIComponent(fileId)}/share-link`, {
    method: "POST"
  }),
  nativeZimbraBriefcaseShares: (resourceId = "") =>
    request<{ shares: NativeZimbraShareEntry[] }>(`/native-zimbra/shares/briefcase${resourceId ? `?resource_id=${encodeURIComponent(resourceId)}` : ""}`),
  nativeZimbraMountedBriefcaseShares: () => request<{ folders: DriveFile[] }>("/native-zimbra/shares/briefcase/mounted"),
  nativeZimbraOutgoingBriefcaseShares: () => request<{ shares: NativeZimbraShareEntry[] }>("/native-zimbra/shares/briefcase/outgoing"),
  nativeZimbraUnmountBriefcaseShare: (resourceId: string) =>
    request<{ folders: DriveFile[] }>(`/native-zimbra/shares/briefcase/mounted/${encodeURIComponent(resourceId)}`, {
      method: "DELETE"
    }),
  nativeZimbraShareBriefcase: (payload: { resource_id: string; email: string; permissions: string }) =>
    request<{ shares: NativeZimbraShareEntry[] }>("/native-zimbra/shares/briefcase", {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  nativeZimbraRevokeBriefcaseShare: (payload: { resource_id: string; email: string }) =>
    request<{ shares: NativeZimbraShareEntry[] }>("/native-zimbra/shares/briefcase", {
      method: "DELETE",
      body: JSON.stringify(payload)
    }),
  nativeZimbraTasks: (payload?: { folder_id?: string; limit?: number; offset?: number; q?: string }) => {
    const search = new URLSearchParams();
    if (payload) {
      for (const [key, value] of Object.entries(payload)) {
        if (value == null || value === "") continue;
        search.set(key, String(value));
      }
    }
    return request<{ tasks: NativeZimbraTask[] }>(`/native-zimbra/tasks${search.toString() ? `?${search.toString()}` : ""}`);
  },
  nativeZimbraTaskLists: () => request<{ lists: NativeZimbraTaskList[] }>("/native-zimbra/tasks/lists"),
  createNativeZimbraTaskList: (payload: { name: string }) =>
    request<{ list: NativeZimbraTaskList }>("/native-zimbra/tasks/lists", {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  renameNativeZimbraTaskList: (listId: string, payload: { name: string }) =>
    request<{ lists: NativeZimbraTaskList[] }>(`/native-zimbra/tasks/lists/${encodeURIComponent(listId)}`, {
      method: "PATCH",
      body: JSON.stringify(payload)
    }),
  updateNativeZimbraTaskListColor: (listId: string, payload: { color: number; rgb?: string }) =>
    request<{ lists: NativeZimbraTaskList[] }>(`/native-zimbra/tasks/lists/${encodeURIComponent(listId)}/color`, {
      method: "PATCH",
      body: JSON.stringify(payload)
    }),
  deleteNativeZimbraTaskList: (listId: string) =>
    request<{ lists: NativeZimbraTaskList[] }>(`/native-zimbra/tasks/lists/${encodeURIComponent(listId)}`, {
      method: "DELETE"
    }),
  nativeZimbraTask: (taskId: string, folderId = "") =>
    request<{ task: NativeZimbraTask }>(`/native-zimbra/tasks/${encodeURIComponent(taskId)}${folderId ? `?folder_id=${encodeURIComponent(folderId)}` : ""}`),
  createNativeZimbraTask: (payload: {
    folder_id?: string;
    invite_id?: string;
    subject: string;
    location?: string;
    description?: string;
    due?: string;
    start?: string;
    completed?: string;
    reminder_at?: string;
    status?: string;
    percent_complete?: number;
    priority?: string;
    reminder_minutes?: number;
  }) =>
    request<{ task: NativeZimbraTask }>("/native-zimbra/tasks", {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  updateNativeZimbraTask: (
    taskId: string,
    payload: {
      folder_id?: string;
      invite_id?: string;
      subject: string;
      location?: string;
      description?: string;
      due?: string;
      start?: string;
      completed?: string;
      reminder_at?: string;
      status?: string;
      percent_complete?: number;
      priority?: string;
      reminder_minutes?: number;
    }
  ) =>
    request<{ task: NativeZimbraTask }>(`/native-zimbra/tasks/${encodeURIComponent(taskId)}`, {
      method: "PATCH",
      body: JSON.stringify(payload)
    }),
  deleteNativeZimbraTask: (taskId: string, folderId = "") =>
    request<{ ok: boolean }>(`/native-zimbra/tasks/${encodeURIComponent(taskId)}${folderId ? `?folder_id=${encodeURIComponent(folderId)}` : ""}`, {
      method: "DELETE"
    }),
  driveDeleteFile: (fileId: string) => request<{ ok: boolean }>(`/drive/files/${encodeURIComponent(fileId)}`, {
    method: "DELETE"
  }),
  driveMoveFile: (fileId: string, parentId: string) =>
    request<{ file: DriveFile }>(`/drive/files/${encodeURIComponent(fileId)}/move?parent_id=${encodeURIComponent(parentId)}`, {
      method: "POST"
    }),
  driveUpload: (payload: { filename: string; content_type: string; content_base64: string; folder_id?: string }) =>
    request<{ file: DriveFile }>(`/drive/files/upload${payload.folder_id ? `?folder_id=${encodeURIComponent(payload.folder_id)}` : ""}`, {
      method: "POST",
      body: JSON.stringify(payload)
    }),
  driveSaveAttachment: (uid: string, part: string, folder = "INBOX", folderId = "") =>
    request<{ file: DriveFile }>(`/drive/messages/${encodeURIComponent(uid)}/attachments/${encodeURIComponent(part)}/save?folder=${encodeURIComponent(folder)}${folderId ? `&folder_id=${encodeURIComponent(folderId)}` : ""}`, {
      method: "POST"
    }),
  createCalendarEvent: (payload: {
    calendar_id: string;
    summary: string;
    start: string;
    end: string;
    time_zone: string;
    all_day: boolean;
    location?: string;
    description?: string;
    attendees?: string[];
    repeat_pattern?: "none" | "daily" | "weekly" | "monthly" | "yearly";
    repeat_interval?: number;
    repeat_end_mode?: "never" | "on_date" | "after_occurrences";
    repeat_until?: string;
    repeat_occurrences?: number;
    reminder_minutes?: number;
  }) => request<{ event: CalendarEvent }>("/calendar/events", {
    method: "POST",
    body: JSON.stringify(payload)
  }),
  calendarReminders: () => request<{ notifications: CalendarReminderNotification[] }>("/calendar/reminders"),
  ackCalendarReminder: (notificationId: string) =>
    request<{ ok: boolean }>(`/calendar/reminders/${encodeURIComponent(notificationId)}/ack`, {
      method: "POST",
    }),
  getCalendarEvent: (eventId: string, calendarId = "primary", timeZone = DEFAULT_TIME_ZONE) =>
    request<{ event: CalendarEvent }>(
      `/calendar/events/${encodeURIComponent(eventId)}?calendar_id=${encodeURIComponent(calendarId)}&time_zone=${encodeURIComponent(timeZone)}`
    ),
  updateCalendarEvent: (eventId: string, payload: {
    calendar_id: string;
    summary: string;
    start: string;
    end: string;
    time_zone: string;
    all_day: boolean;
    location?: string;
    description?: string;
    attendees?: string[];
    repeat_pattern?: "none" | "daily" | "weekly" | "monthly" | "yearly";
    repeat_interval?: number;
    repeat_end_mode?: "never" | "on_date" | "after_occurrences";
    repeat_until?: string;
    repeat_occurrences?: number;
    reminder_minutes?: number;
  }) => request<{ event: CalendarEvent }>(`/calendar/events/${encodeURIComponent(eventId)}`, {
    method: "PATCH",
    body: JSON.stringify(payload)
  }),
  deleteCalendarEvent: (eventId: string, calendarId: string, scope: "this" | "series" = "series") => request<{ ok: boolean }>(`/calendar/events/${encodeURIComponent(eventId)}?calendar_id=${encodeURIComponent(calendarId)}&scope=${encodeURIComponent(scope)}`, {
    method: "DELETE"
  }),
  adminOrganizations: (adminKey: string) =>
    request<{ organizations: Organization[] }>("/admin/organizations", { headers: { "X-Platform-Key": adminKey } }),
  adminCreateOrganization: (adminKey: string, payload: { name: string; primary_domain?: string; timezone?: string; plan_code?: string; billing_provider?: string }) =>
    request<{ organization: Organization; admin_token: string }>("/admin/organizations", {
      method: "POST",
      headers: { "X-Platform-Key": adminKey },
      body: JSON.stringify(payload)
    }),
  adminOrganization: (adminKey: string, orgId: string) =>
    request<Organization>(`/admin/organizations/${encodeURIComponent(orgId)}`, { headers: { "X-Platform-Key": adminKey } }),
  adminUpdateOrganization: (adminKey: string, orgId: string, payload: Partial<Organization>) =>
    request<Organization>(`/admin/organizations/${encodeURIComponent(orgId)}`, {
      method: "PATCH",
      headers: { "X-Platform-Key": adminKey },
      body: JSON.stringify(payload)
    }),
  adminSuspendOrganization: (adminKey: string, orgId: string) =>
    request<Organization>(`/admin/organizations/${encodeURIComponent(orgId)}/suspend`, { method: "POST", headers: { "X-Platform-Key": adminKey } }),
  adminResumeOrganization: (adminKey: string, orgId: string) =>
    request<Organization>(`/admin/organizations/${encodeURIComponent(orgId)}/resume`, { method: "POST", headers: { "X-Platform-Key": adminKey } }),
  adminDomains: (adminKey: string, orgId: string) =>
    request<{ domains: Domain[] }>(`/admin/organizations/${encodeURIComponent(orgId)}/domains`, { headers: { "X-Platform-Key": adminKey } }),
  adminCreateDomain: (adminKey: string, orgId: string, payload: { domain_name: string }) =>
    request<{ domain: Domain }>(`/admin/organizations/${encodeURIComponent(orgId)}/domains`, {
      method: "POST",
      headers: { "X-Platform-Key": adminKey },
      body: JSON.stringify(payload)
    }),
  adminVerifyDomain: (adminKey: string, orgId: string, domainId: string) =>
    request<{ domain: Domain }>(`/admin/organizations/${encodeURIComponent(orgId)}/domains/${encodeURIComponent(domainId)}/verify`, {
      method: "POST",
      headers: { "X-Platform-Key": adminKey }
    }),
  adminMailboxes: (adminKey: string, orgId: string) =>
    request<{ mailboxes: Mailbox[] }>(`/admin/organizations/${encodeURIComponent(orgId)}/mailboxes`, { headers: { "X-Platform-Key": adminKey } }),
  adminCreateMailbox: (adminKey: string, orgId: string, payload: { domain_id: string; local_part: string; display_name?: string; quota_mb?: number }) =>
    request<{ mailbox: Mailbox }>(`/admin/organizations/${encodeURIComponent(orgId)}/mailboxes`, {
      method: "POST",
      headers: { "X-Platform-Key": adminKey },
      body: JSON.stringify(payload)
    }),
  adminUpdateMailbox: (adminKey: string, orgId: string, mailboxId: string, payload: { display_name?: string; quota_mb?: number; status?: string }) =>
    request<{ mailbox: Mailbox }>(`/admin/organizations/${encodeURIComponent(orgId)}/mailboxes/${encodeURIComponent(mailboxId)}`, {
      method: "PATCH",
      headers: { "X-Platform-Key": adminKey },
      body: JSON.stringify(payload)
    }),
  adminDisableMailbox: (adminKey: string, orgId: string, mailboxId: string) =>
    request<{ mailbox: Mailbox }>(`/admin/organizations/${encodeURIComponent(orgId)}/mailboxes/${encodeURIComponent(mailboxId)}/disable`, {
      method: "POST",
      headers: { "X-Platform-Key": adminKey }
    }),
  adminEnableMailbox: (adminKey: string, orgId: string, mailboxId: string) =>
    request<{ mailbox: Mailbox }>(`/admin/organizations/${encodeURIComponent(orgId)}/mailboxes/${encodeURIComponent(mailboxId)}/enable`, {
      method: "POST",
      headers: { "X-Platform-Key": adminKey }
    }),
  adminDeleteMailbox: (adminKey: string, orgId: string, mailboxId: string) =>
    request<{ ok: boolean }>(`/admin/organizations/${encodeURIComponent(orgId)}/mailboxes/${encodeURIComponent(mailboxId)}`, {
      method: "DELETE",
      headers: { "X-Platform-Key": adminKey }
    }),
  adminBilling: (adminKey: string, orgId: string) =>
    request<{ organization: Organization; subscription: Subscription; invoices: InvoiceRecord[]; billing_events: BillingEvent[]; audit_logs: Array<Record<string, unknown>> }>(`/admin/organizations/${encodeURIComponent(orgId)}/billing`, { headers: { "X-Platform-Key": adminKey } }),
  adminProvisioning: (adminKey: string, orgId: string) =>
    request<ProvisioningSummary>(`/admin/organizations/${encodeURIComponent(orgId)}/provisioning`, { headers: { "X-Platform-Key": adminKey } }),
  adminRunProvisioning: (adminKey: string, orgId: string) =>
    request<ProvisioningSummary>(`/admin/organizations/${encodeURIComponent(orgId)}/provisioning/run`, { method: "POST", headers: { "X-Platform-Key": adminKey } }),
  adminAuditLogs: (adminKey: string, orgId: string) =>
    request<{ audit_logs: Array<Record<string, unknown>> }>(`/admin/organizations/${encodeURIComponent(orgId)}/audit-logs`, { headers: { "X-Platform-Key": adminKey } }),
  adminMailMigrations: (adminKey: string, orgId: string) =>
    request<{ jobs: MailMigrationJob[] }>(`/admin/organizations/${encodeURIComponent(orgId)}/mail-migrations`, { headers: { "X-Platform-Key": adminKey } }),
  adminTestMailMigrationConnection: (adminKey: string, orgId: string, payload: {
    mailbox_email: string;
    mailbox_password: string;
    label?: string;
    source_host: string;
    source_port: number;
    source_security: "ssl" | "starttls" | "plain";
    source_skip_ssl_verify?: boolean;
    source_username: string;
    source_password: string;
    dry_run?: boolean;
    include_folders?: string[];
    exclude_folders?: string[];
  }) =>
    request<MailMigrationConnectionResult>(`/admin/organizations/${encodeURIComponent(orgId)}/mail-migrations/test-connection`, {
      method: "POST",
      headers: { "X-Platform-Key": adminKey },
      body: JSON.stringify(payload)
    }),
  adminStartMailMigration: (adminKey: string, orgId: string, payload: {
    mailbox_email: string;
    mailbox_password: string;
    label?: string;
    source_host: string;
    source_port: number;
    source_security: "ssl" | "starttls" | "plain";
    source_skip_ssl_verify?: boolean;
    source_username: string;
    source_password: string;
    dry_run?: boolean;
    include_folders?: string[];
    exclude_folders?: string[];
  }) =>
    request<{ job: MailMigrationJob }>(`/admin/organizations/${encodeURIComponent(orgId)}/mail-migrations`, {
      method: "POST",
      headers: { "X-Platform-Key": adminKey },
      body: JSON.stringify(payload)
    }),
  adminStartBulkMailMigration: (adminKey: string, orgId: string, payload: {
    jobs: Array<{
      mailbox_email: string;
      mailbox_password: string;
      label?: string;
      source_host: string;
      source_port: number;
      source_security: "ssl" | "starttls" | "plain";
      source_skip_ssl_verify?: boolean;
      source_username: string;
      source_password: string;
      dry_run?: boolean;
      include_folders?: string[];
      exclude_folders?: string[];
    }>;
  }) =>
    request<{ jobs: MailMigrationJob[]; errors: Array<{ mailbox_email: string; detail: string }> }>(`/admin/organizations/${encodeURIComponent(orgId)}/mail-migrations/bulk`, {
      method: "POST",
      headers: { "X-Platform-Key": adminKey },
      body: JSON.stringify(payload)
    }),
  adminSessionToken: (adminKey: string, orgId: string) =>
    request<{ admin_token: string }>(`/admin/organizations/${encodeURIComponent(orgId)}/admin-session`, { method: "POST", headers: { "X-Platform-Key": adminKey } }),
  adminBillingSync: (adminKey: string, orgId: string) =>
    request<Record<string, unknown>>(`/admin/organizations/${encodeURIComponent(orgId)}/billing/sync`, { method: "POST", headers: { "X-Platform-Key": adminKey } }),
  adminBillingCheckout: (adminKey: string, orgId: string, payload: { success_url?: string; cancel_url?: string }) =>
    request<Record<string, unknown>>(`/admin/organizations/${encodeURIComponent(orgId)}/billing/checkout`, { method: "POST", headers: { "X-Platform-Key": adminKey }, body: JSON.stringify(payload) }),
  adminBillingSession: (adminKey: string, orgId: string, payload: { return_url?: string }) =>
    request<Record<string, unknown>>(`/admin/organizations/${encodeURIComponent(orgId)}/billing/session`, { method: "POST", headers: { "X-Platform-Key": adminKey }, body: JSON.stringify(payload) }),
  adminSmokeTestGateway: (adminKey: string, orgId: string, domainId: string) =>
    request<Record<string, unknown>>(`/admin/organizations/${encodeURIComponent(orgId)}/domains/${encodeURIComponent(domainId)}/provisioning/smoke-test`, { method: "POST", headers: { "X-Platform-Key": adminKey } }),
  tenantAdminLogin: (payload: { email: string; password: string; zimbra_soap_url?: string; zimbra_verify_ssl?: boolean }) =>
    request<TenantAdminLoginResponse>("/admin/login", {
      method: "POST",
      body: JSON.stringify(payload),
    }),
  tenantAdminLoginTwoFactor: (payload: { challenge_token: string; code: string }) =>
    request<TenantAdminLoginResponse>("/admin/login/2fa", {
      method: "POST",
      body: JSON.stringify(payload),
    }),
  tenantAdminMe: (adminToken: string) => request<{ organization: Organization }>("/admin/me", { headers: tenantAdminHeaders(adminToken) }),
  tenantAdminOrganization: (adminToken: string) => request<{ organization: Organization }>("/admin/organization", { headers: tenantAdminHeaders(adminToken) }),
  tenantAdminUpdateOrganization: (adminToken: string, payload: Partial<Organization>) =>
    request<{ organization: Organization }>("/admin/organization", { method: "PATCH", headers: tenantAdminHeaders(adminToken), body: JSON.stringify(payload) }),
  tenantAdminUpdateBranding: (adminToken: string, payload: { name: string; tagline: string; login_theme: string; login_landscape_only?: boolean; login_design_mode?: "theme" | "custom"; login_template?: "panel-left" | "panel-right" | "centered" | "split"; login_background_color?: string; login_gradient_color?: string; login_brand_name_color?: string; login_tagline_color?: string; login_supporting_text_color?: string; login_box_transparency?: number; domain?: string }) =>
    request<{ branding: AppConfig["branding"] }>("/admin/branding", { method: "PATCH", headers: tenantAdminHeaders(adminToken), body: JSON.stringify(payload) }),
  tenantAdminUploadBrandLogo: (adminToken: string, file: File, alt = "", domain = "") => {
    const body = new FormData();
    body.append("file", file);
    body.append("alt", alt);
    body.append("domain", domain);
    return requestFormData<{ branding: AppConfig["branding"] }>("/admin/branding/logo", body, {
      headers: tenantAdminHeaders(adminToken),
    });
  },
  tenantAdminUploadLoginBackground: (adminToken: string, file: File, domain = "") => {
    const body = new FormData();
    body.append("file", file);
    body.append("domain", domain);
    return requestFormData<{ branding: AppConfig["branding"] }>("/admin/branding/login-background", body, { headers: tenantAdminHeaders(adminToken) });
  },
  tenantAdminDomains: (adminToken: string) => request<{ domains: Domain[] }>("/admin/domains", { headers: tenantAdminHeaders(adminToken) }),
  tenantAdminCreateDomain: (adminToken: string, payload: { domain_name: string }) => request<{ domain: Domain }>("/admin/domains", { method: "POST", headers: tenantAdminHeaders(adminToken), body: JSON.stringify(payload) }),
  tenantAdminVerifyDomain: (adminToken: string, domainId: string) => request<{ domain: Domain }>(`/admin/domains/${encodeURIComponent(domainId)}/verify`, { method: "POST", headers: tenantAdminHeaders(adminToken) }),
  tenantAdminMailboxes: (adminToken: string, q = "") =>
    request<{ mailboxes: Mailbox[] }>(`/admin/mailboxes${q ? `?q=${encodeURIComponent(q)}` : ""}`, { headers: tenantAdminHeaders(adminToken) }),
  tenantAdminCreateMailbox: (adminToken: string, payload: { domain_id: string; local_part: string; display_name?: string; quota_mb?: number; password: string }) => request<{ mailbox: Mailbox }>("/admin/mailboxes", { method: "POST", headers: tenantAdminHeaders(adminToken), body: JSON.stringify(payload) }),
  tenantAdminUpdateMailbox: (adminToken: string, mailboxId: string, payload: { display_name?: string; quota_mb?: number; status?: string }) => request<{ mailbox: Mailbox }>(`/admin/mailboxes/${encodeURIComponent(mailboxId)}`, { method: "PATCH", headers: tenantAdminHeaders(adminToken), body: JSON.stringify(payload) }),
  tenantAdminUpdateMailboxPassword: (adminToken: string, mailboxId: string, payload: { password: string }) =>
    request<{ ok: boolean }>(`/admin/mailboxes/${encodeURIComponent(mailboxId)}/password`, {
      method: "PATCH",
      headers: tenantAdminHeaders(adminToken),
      body: JSON.stringify(payload)
    }),
  tenantAdminRenameMailbox: (adminToken: string, mailboxId: string, payload: { local_part: string }) =>
    request<{ mailbox: Mailbox }>(`/admin/mailboxes/${encodeURIComponent(mailboxId)}/rename`, {
      method: "PATCH",
      headers: tenantAdminHeaders(adminToken),
      body: JSON.stringify(payload)
    }),
  tenantAdminAddMailboxAlias: (adminToken: string, mailboxId: string, payload: { alias: string }) =>
    request<{ mailbox: Mailbox }>(`/admin/mailboxes/${encodeURIComponent(mailboxId)}/aliases`, {
      method: "POST",
      headers: tenantAdminHeaders(adminToken),
      body: JSON.stringify(payload)
    }),
  tenantAdminRemoveMailboxAlias: (adminToken: string, mailboxId: string, alias: string) =>
    request<{ mailbox: Mailbox }>(`/admin/mailboxes/${encodeURIComponent(mailboxId)}/aliases/${encodeURIComponent(alias)}`, {
      method: "DELETE",
      headers: tenantAdminHeaders(adminToken)
    }),
  tenantAdminUpdateMailboxForwarding: (adminToken: string, mailboxId: string, payload: { addresses: string[]; keep_local_copy: boolean }) =>
    request<{ mailbox: Mailbox }>(`/admin/mailboxes/${encodeURIComponent(mailboxId)}/forwarding`, {
      method: "PATCH",
      headers: tenantAdminHeaders(adminToken),
      body: JSON.stringify(payload)
    }),
  tenantAdminDisableMailboxTwoFactor: (adminToken: string, mailboxId: string) =>
    request<{ ok: boolean }>(`/admin/mailboxes/${encodeURIComponent(mailboxId)}/2fa`, {
      method: "DELETE",
      headers: tenantAdminHeaders(adminToken),
    }),
  tenantAdminUpdateMailboxTwoFactorRequired: (adminToken: string, mailboxId: string, payload: { required: boolean }) =>
    request<{ ok: boolean; mailbox?: Mailbox }>(`/admin/mailboxes/${encodeURIComponent(mailboxId)}/2fa/required`, {
      method: "PATCH",
      headers: tenantAdminHeaders(adminToken),
      body: JSON.stringify(payload),
    }),
  tenantAdminUpdateMailboxRole: (adminToken: string, mailboxId: string, payload: { role: string }) =>
    request<{ mailbox: Mailbox }>(`/admin/mailboxes/${encodeURIComponent(mailboxId)}/role`, {
      method: "PATCH",
      headers: tenantAdminHeaders(adminToken),
      body: JSON.stringify(payload)
    }),
  tenantAdminDisableMailbox: (adminToken: string, mailboxId: string) => request<{ mailbox: Mailbox }>(`/admin/mailboxes/${encodeURIComponent(mailboxId)}/disable`, { method: "POST", headers: tenantAdminHeaders(adminToken) }),
  tenantAdminEnableMailbox: (adminToken: string, mailboxId: string) => request<{ mailbox: Mailbox }>(`/admin/mailboxes/${encodeURIComponent(mailboxId)}/enable`, { method: "POST", headers: tenantAdminHeaders(adminToken) }),
  tenantAdminDeleteMailbox: (adminToken: string, mailboxId: string) => request<{ ok: boolean }>(`/admin/mailboxes/${encodeURIComponent(mailboxId)}`, { method: "DELETE", headers: tenantAdminHeaders(adminToken) }),
  tenantAdminDistributionLists: (adminToken: string, q = "") =>
    request<{ distribution_lists: DistributionList[] }>(`/admin/distribution-lists${q ? `?q=${encodeURIComponent(q)}` : ""}`, { headers: tenantAdminHeaders(adminToken) }),
  tenantAdminCreateDistributionList: (adminToken: string, payload: { domain_id: string; local_part: string; display_name?: string }) =>
    request<{ distribution_list: DistributionList }>("/admin/distribution-lists", {
      method: "POST",
      headers: tenantAdminHeaders(adminToken),
      body: JSON.stringify(payload),
    }),
  tenantAdminDeleteDistributionList: (adminToken: string, email: string) =>
    request<{ ok: boolean }>(`/admin/distribution-lists/${encodeURIComponent(email)}`, {
      method: "DELETE",
      headers: tenantAdminHeaders(adminToken),
    }),
  tenantAdminAddDistributionListMember: (adminToken: string, email: string, memberEmail: string) =>
    request<{ distribution_list: DistributionList }>(`/admin/distribution-lists/${encodeURIComponent(email)}/members`, {
      method: "POST",
      headers: tenantAdminHeaders(adminToken),
      body: JSON.stringify({ member_email: memberEmail }),
    }),
  tenantAdminRemoveDistributionListMember: (adminToken: string, email: string, memberEmail: string) =>
    request<{ distribution_list: DistributionList }>(`/admin/distribution-lists/${encodeURIComponent(email)}/members/${encodeURIComponent(memberEmail)}`, {
      method: "DELETE",
      headers: tenantAdminHeaders(adminToken),
    }),
  tenantAdminBilling: (adminToken: string) => request<Record<string, unknown>>("/admin/billing", { headers: tenantAdminHeaders(adminToken) }),
  tenantAdminProvisioning: (adminToken: string) => request<ProvisioningSummary>("/admin/provisioning", { headers: tenantAdminHeaders(adminToken) }),
  tenantAdminBillingCheckout: (adminToken: string) => request<Record<string, unknown>>("/admin/billing/checkout", { method: "POST", headers: tenantAdminHeaders(adminToken) }),
  tenantAdminBillingSession: (adminToken: string) => request<Record<string, unknown>>("/admin/billing/session", { method: "POST", headers: tenantAdminHeaders(adminToken) })
};
