import { apiEndpoints } from "@/lib/api/endpoints";
import { fetchWithAuth } from "@/lib/auth/client";
import type {
  AdminCreatePayload,
  AdminUpdatePayload,
  ApiRole,
  ApiUser,
  PaginatedResponse,
  ProfileOverviewResponse,
  SuccessMessage,
} from "@/types/api";

function normalizeUser(user: Partial<ApiUser> & { id?: string }) {
  return {
    ...user,
    _id: user._id ?? user.id ?? "",
  } as ApiUser;
}

function normalizeUsersResponse(response: PaginatedResponse<ApiUser>) {
  return {
    ...response,
    items: Array.isArray(response.items) ? response.items.map((item) => normalizeUser(item)) : response.items,
    data: Array.isArray(response.data) ? response.data.map((item) => normalizeUser(item)) : response.data,
  };
}

export async function listPlatformAdmins(page = 1, limit = 20) {
  const response = await fetchWithAuth<PaginatedResponse<ApiUser>>(
    apiEndpoints.users.admins({ page, limit }),
  );
  return normalizeUsersResponse(response);
}

export async function getAdminUserById(userId: string) {
  const response = await fetchWithAuth<ApiUser>(apiEndpoints.users.byId(userId));
  return normalizeUser(response);
}

export async function updateAdminUser(userId: string, payload: AdminUpdatePayload) {
  const response = await fetchWithAuth<ApiUser>(apiEndpoints.users.update(userId), {
    method: "PATCH",
    body: JSON.stringify(payload),
  });
  return normalizeUser(response);
}

export async function updatePlatformAdmin(userId: string, payload: AdminUpdatePayload) {
  const response = await fetchWithAuth<ApiUser>(apiEndpoints.users.updateAdmin(userId), {
    method: "PATCH",
    body: JSON.stringify(payload),
  });
  return normalizeUser(response);
}

export async function setAdminUserRole(userId: string, role: ApiRole) {
  const response = await fetchWithAuth<ApiUser>(apiEndpoints.users.setRole(userId), {
    method: "PATCH",
    body: JSON.stringify({ role }),
  });
  return normalizeUser(response);
}

export async function deleteAdminUser(userId: string) {
  return fetchWithAuth<SuccessMessage>(apiEndpoints.users.remove(userId), { method: "DELETE" });
}

export async function deletePlatformAdmin(userId: string) {
  return fetchWithAuth<SuccessMessage>(apiEndpoints.users.removeAdmin(userId), { method: "DELETE" });
}

export async function createAdminUser(payload: AdminCreatePayload) {
  const response = await fetchWithAuth<ApiUser>(apiEndpoints.users.createAdmin, {
    method: "POST",
    body: JSON.stringify(payload),
  });
  return normalizeUser(response);
}

export async function searchAdminUsers(params: Record<string, string | number | boolean | null | undefined>) {
  const response = await fetchWithAuth<PaginatedResponse<ApiUser>>(apiEndpoints.users.all(params));
  return normalizeUsersResponse(response);
}

export async function discoverAdminUsers(params: Record<string, string | number | boolean | null | undefined>) {
  const response = await fetchWithAuth<PaginatedResponse<ApiUser>>(apiEndpoints.users.discover(params));
  return normalizeUsersResponse(response);
}

export async function searchPlatformAdmins(params: Record<string, string | number | boolean | null | undefined>) {
  const response = await fetchWithAuth<PaginatedResponse<ApiUser>>(apiEndpoints.users.admins(params));
  return normalizeUsersResponse(response);
}

export async function getProfileOverviewForSuperAdmin(userId: string) {
  return fetchWithAuth<ProfileOverviewResponse>(apiEndpoints.users.profileOverview(userId));
}
