import { apiEndpoints } from "@/lib/api/endpoints";
import { fetchWithAuth } from "@/lib/auth/client";
import type {
  ApiComment,
  ApiPost,
  ApiUser,
  CreateSuperAdminCasePayload,
  ModerationStatus,
  SuperAdminCase,
  SuperAdminCasesResponse,
  SuperAdminChartsResponse,
  SuperAdminOpsResponse,
  SuperAdminOverviewResponse,
  SuperAdminRecentActivityResponse,
  SuperAdminReportsResponse,
  SuperAdminSessionResponse,
  SuperAdminSettings,
  SuperAdminSettingsHistoryResponse,
  SuperAdminSettingsResponse,
} from "@/types/api";

export async function getSuperAdminSession() {
  return fetchWithAuth<SuperAdminSessionResponse>(apiEndpoints.superadmin.session);
}

export async function getSuperAdminOverview() {
  return fetchWithAuth<SuperAdminOverviewResponse>(apiEndpoints.superadmin.overview);
}

export async function getSuperAdminCharts(
  params: Record<string, string | number | boolean | null | undefined> = {},
) {
  return fetchWithAuth<SuperAdminChartsResponse>(apiEndpoints.superadmin.charts(params));
}

export async function getSuperAdminRecentActivity(
  params: Record<string, string | number | boolean | null | undefined> = {},
) {
  return fetchWithAuth<SuperAdminRecentActivityResponse>(apiEndpoints.superadmin.recentActivity(params));
}

export async function getSuperAdminReports(
  params: Record<string, string | number | boolean | null | undefined> = {},
) {
  return fetchWithAuth<SuperAdminReportsResponse>(apiEndpoints.superadmin.reports(params));
}

export async function getSuperAdminOps() {
  return fetchWithAuth<SuperAdminOpsResponse>(apiEndpoints.superadmin.ops);
}

export async function getSuperAdminCases(
  params: Record<string, string | number | boolean | null | undefined> = {},
) {
  return fetchWithAuth<SuperAdminCasesResponse>(apiEndpoints.superadmin.cases(params));
}

export async function createSuperAdminCase(payload: CreateSuperAdminCasePayload) {
  return fetchWithAuth<SuperAdminCase>(apiEndpoints.superadmin.createCase, {
    method: "POST",
    body: JSON.stringify(payload),
  });
}

export async function updateSuperAdminCase(
  caseId: string,
  payload: Partial<SuperAdminCase> & { note?: string },
) {
  return fetchWithAuth<SuperAdminCase>(apiEndpoints.superadmin.caseById(caseId), {
    method: "PATCH",
    body: JSON.stringify(payload),
  });
}

export async function performSuperAdminBulkAction(payload: {
  resourceType: string;
  targetIds: string[];
  action: string;
  reason?: string;
  priority?: string;
  assignToMe?: boolean;
}) {
  return fetchWithAuth<Record<string, unknown>>(apiEndpoints.superadmin.bulkActions, {
    method: "POST",
    body: JSON.stringify(payload),
  });
}

export async function getSuperAdminSettings() {
  return fetchWithAuth<SuperAdminSettingsResponse>(apiEndpoints.superadmin.settings);
}

export async function getSuperAdminSettingsHistory(
  params: Record<string, string | number | boolean | null | undefined> = {},
) {
  return fetchWithAuth<SuperAdminSettingsHistoryResponse>(
    apiEndpoints.superadmin.settingsHistory(params),
  );
}

export async function updateSuperAdminSettings(payload: Partial<SuperAdminSettings>) {
  return fetchWithAuth<SuperAdminSettingsResponse>(apiEndpoints.superadmin.settings, {
    method: "PATCH",
    body: JSON.stringify(payload),
  });
}

export async function restoreSuperAdminSettingsHistory(historyId: string) {
  return fetchWithAuth<SuperAdminSettingsResponse>(
    apiEndpoints.superadmin.restoreSettingsHistory(historyId),
    {
      method: "POST",
    },
  );
}

export async function updateSuperAdminPostStatus(postId: string, status: ModerationStatus, reason?: string) {
  return fetchWithAuth<ApiPost>(apiEndpoints.superadmin.updatePostStatus(postId), {
    method: "PATCH",
    body: JSON.stringify({ status, reason }),
  });
}

export async function deleteSuperAdminPost(postId: string) {
  return fetchWithAuth<Record<string, unknown>>(apiEndpoints.superadmin.deletePost(postId), {
    method: "DELETE",
  });
}

export async function restoreSuperAdminPost(postId: string) {
  return fetchWithAuth<ApiPost>(apiEndpoints.superadmin.restorePost(postId), {
    method: "POST",
  });
}

export async function updateSuperAdminCommentStatus(
  commentId: string,
  status: ModerationStatus,
  reason?: string,
) {
  return fetchWithAuth<ApiComment>(apiEndpoints.superadmin.updateCommentStatus(commentId), {
    method: "PATCH",
    body: JSON.stringify({ status, reason }),
  });
}

export async function deleteSuperAdminComment(commentId: string) {
  return fetchWithAuth<Record<string, unknown>>(apiEndpoints.superadmin.deleteComment(commentId), {
    method: "DELETE",
  });
}

export async function restoreSuperAdminComment(commentId: string) {
  return fetchWithAuth<ApiComment>(apiEndpoints.superadmin.restoreComment(commentId), {
    method: "POST",
  });
}

export async function updateSuperAdminUserStatus(userId: string, isDisabled: boolean, reason?: string) {
  try {
    return await fetchWithAuth<ApiUser>(apiEndpoints.superadmin.updateUserStatus(userId), {
      method: "PATCH",
      body: JSON.stringify({ isDisabled, reason }),
    });
  } catch (error) {
    const message = String(error);
    if (!message.includes("404")) {
      throw error;
    }

    if (isDisabled) {
      return fetchWithAuth<ApiUser>(apiEndpoints.users.disable(userId), {
        method: "PATCH",
        body: JSON.stringify({ reason: reason ?? "Disabled by SuperAdmin dashboard" }),
      });
    }

    return fetchWithAuth<ApiUser>(apiEndpoints.users.enable(userId), {
      method: "PATCH",
    });
  }
}
