/**
 * Admin API Client
 * Handles admin user management requests
 */

import type { WorkspaceMemberRole } from "@mosaic/shared";
import { apiGet, apiPatch, apiPost, apiDelete } from "./client";

export interface AdminWorkspaceMembership {
  workspaceId: string;
  workspaceName: string;
  role: WorkspaceMemberRole;
  joinedAt: string;
}

export interface AdminUser {
  id: string;
  name: string;
  email: string;
  emailVerified: boolean;
  image: string | null;
  createdAt: string;
  deactivatedAt: string | null;
  isLocalAuth: boolean;
  invitedAt: string | null;
  invitedBy: string | null;
  workspaceMemberships: AdminWorkspaceMembership[];
}

export interface AdminUsersResponse {
  data: AdminUser[];
  meta: {
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  };
}

export interface InviteUserDto {
  email: string;
  name?: string;
  workspaceId?: string;
  role?: WorkspaceMemberRole;
}

export interface InvitationResponse {
  userId: string;
  invitationToken: string;
  email: string;
  invitedAt: string;
}

export interface UpdateUserDto {
  name?: string;
  email?: string;
  deactivatedAt?: string | null;
  emailVerified?: boolean;
  preferences?: Record<string, unknown>;
}

/**
 * Fetch paginated admin users
 */
export async function fetchAdminUsers(page?: number, limit?: number): Promise<AdminUsersResponse> {
  const params = new URLSearchParams();

  if (page !== undefined) {
    params.append("page", String(page));
  }

  if (limit !== undefined) {
    params.append("limit", String(limit));
  }

  const endpoint = `/api/admin/users${params.toString() ? `?${params.toString()}` : ""}`;
  return apiGet<AdminUsersResponse>(endpoint);
}

/**
 * Invite a user by email
 */
export async function inviteUser(dto: InviteUserDto): Promise<InvitationResponse> {
  return apiPost<InvitationResponse>("/api/admin/users/invite", dto);
}

/**
 * Update admin user fields
 */
export async function updateUser(id: string, dto: UpdateUserDto): Promise<AdminUser> {
  return apiPatch<AdminUser>(`/api/admin/users/${id}`, dto);
}

/**
 * Deactivate a user account
 */
export async function deactivateUser(id: string): Promise<AdminUser> {
  return apiDelete<AdminUser>(`/api/admin/users/${id}`);
}
