import type {
  AdminBlockUserInput,
  AdminComplexListItem,
  AdminCreatePlanInput,
  AdminGeoStats,
  AdminGlobalStats,
  AdminUpdatePlanInput,
  AdminUser,
  AdminUserSession,
} from '@repo/api-contract';
import { http } from '../http';

type AdminPlan = {
  code: string;
  name: string;
  price: number;
  rules: unknown;
  lastUpdatedAt: string;
  complexCount: number;
};

export async function listComplexes() {
  const response = await http.get<AdminComplexListItem[]>('/api/admin/complexes');
  return response.data;
}

export async function listPlans() {
  const response = await http.get<AdminPlan[]>('/api/admin/plans');
  return response.data;
}

export async function createPlan(data: AdminCreatePlanInput) {
  const response = await http.post<{ code: string; name: string; price: number }>(
    '/api/admin/plans',
    JSON.stringify(data),
    { headers: { 'Content-Type': 'application/json' } }
  );
  return response.data;
}

export async function updatePlan(code: string, data: AdminUpdatePlanInput) {
  const response = await http.patch<{ code: string; name: string; price: number }>(
    `/api/admin/plans/${code}`,
    JSON.stringify(data),
    { headers: { 'Content-Type': 'application/json' } }
  );
  return response.data;
}

export async function deletePlan(code: string) {
  const response = await http.delete<{ message: string }>(`/api/admin/plans/${code}`);
  return response.data;
}

export async function listUsers(search?: string) {
  const response = await http.get<AdminUser[]>('/api/admin/users', {
    params: search ? { search } : undefined,
  });
  return response.data;
}

export async function blockUser(userId: string, data?: AdminBlockUserInput) {
  const response = await http.post<{ message: string }>(
    `/api/admin/users/${userId}/block`,
    JSON.stringify(data ?? {}),
    { headers: { 'Content-Type': 'application/json' } }
  );
  return response.data;
}

export async function unblockUser(userId: string) {
  const response = await http.post<{ message: string }>(`/api/admin/users/${userId}/unblock`);
  return response.data;
}

export async function getGlobalStats() {
  const response = await http.get<AdminGlobalStats>('/api/admin/stats');
  return response.data;
}

export async function getGeoStats() {
  const response = await http.get<AdminGeoStats>('/api/admin/geo-stats');
  return response.data;
}

export async function getUserSessions(userId: string) {
  const response = await http.get<AdminUserSession[]>(`/api/admin/users/${userId}/sessions`);
  return response.data;
}

export async function revokeAllSessions(userId: string) {
  const response = await http.post<{ message: string }>(
    `/api/admin/users/${userId}/sessions/revoke-all`
  );
  return response.data;
}
