"use client";

/**
 * Admin-only read API over `user_events` — Feature 2 (login/IP audit) + Feature 3
 * (behavior analytics dashboard). Mirrors `app/api/v1/audit.py` +
 * `app/schemas/audit.py` (tradein-mvp backend, PR #2520). Hand-written types —
 * tradein-mvp/frontend has no `codegen` script (no openapi-typescript wired up,
 * see package.json scripts: dev/build/start/lint/type-check only).
 *
 * All 3 endpoints live under the admin API prefix, gated by the central
 * `rbac_guard` middleware in `app/main.py` (role != admin → 403 regardless of
 * frontend). `retry: false` — a 403 must not re-hammer the backend.
 */

import { useQuery } from "@tanstack/react-query";

import { apiFetch } from "./api";

const BASE = "/api/v1/admin";

// ---- Types (mirror app/schemas/audit.py) ----------------------------------

export interface AccountSummary {
  username: string;
  first_seen_at: string;
  last_seen_at: string;
  distinct_ips: number;
  distinct_devices: number;
  login_count: number;
  request_count: number;
  search_count: number;
}

export interface AccountIpEntry {
  ip_address: string | null;
  event_count: number;
  first_seen: string;
  last_seen: string;
}

export interface AccountDeviceEntry {
  user_agent: string | null;
  event_count: number;
  first_seen: string;
  last_seen: string;
}

export interface AccountSearchEntry {
  address: string | null;
  area_m2: string | null;
  rooms: string | null;
  estimate_id: string | null;
  ip_address: string | null;
  created_at: string;
}

export interface AccountActivityEntry {
  event_type: string;
  path: string | null;
  method: string | null;
  ip_address: string | null;
  created_at: string;
}

export interface AccountDrilldown {
  ips: AccountIpEntry[];
  devices: AccountDeviceEntry[];
  searches: AccountSearchEntry[];
  recent_activity: AccountActivityEntry[];
}

export interface AnalyticsSummary {
  total_events: number;
  distinct_users: number;
  events_last_24h: number;
  active_users_last_24h: number;
}

export interface AnalyticsDailyPoint {
  day: string;
  events: number;
  users: number;
}

export interface AnalyticsTopSearch {
  address: string | null;
  n: number;
}

export interface AnalyticsTopPath {
  path: string | null;
  n: number;
}

export interface AnalyticsByAccount {
  username: string;
  events: number;
  searches: number;
  last_seen: string;
}

export interface AnalyticsDashboard {
  summary: AnalyticsSummary;
  daily: AnalyticsDailyPoint[];
  top_searches: AnalyticsTopSearch[];
  top_paths: AnalyticsTopPath[];
  by_account: AnalyticsByAccount[];
}

// ---- Hooks ------------------------------------------------------------------

/**
 * GET /api/v1/admin/audit/accounts
 * Список аккаунтов, по одной строке на username — сводка активности (Feature 2).
 */
export function useAuditAccounts() {
  return useQuery<AccountSummary[]>({
    queryKey: ["admin", "audit", "accounts"],
    queryFn: () => apiFetch<AccountSummary[]>(`${BASE}/audit/accounts`),
    staleTime: 30_000,
    retry: false,
  });
}

/**
 * GET /api/v1/admin/audit/accounts/{username}
 * Drilldown по одному аккаунту: IP, устройства, поиски, недавняя активность.
 * `enabled: false` пока username === null — используется для ленивого раскрытия
 * строки в таблице аккаунтов.
 */
export function useAccountDrilldown(username: string | null) {
  return useQuery<AccountDrilldown>({
    queryKey: ["admin", "audit", "accounts", username],
    queryFn: () =>
      apiFetch<AccountDrilldown>(
        `${BASE}/audit/accounts/${encodeURIComponent(username as string)}`,
      ),
    enabled: username !== null && username.length > 0,
    staleTime: 30_000,
    retry: false,
  });
}

/**
 * GET /api/v1/admin/analytics?days=N
 * Feature 3 dashboard bundle: сводка, дневной time-series, топ-поиски/пути/аккаунты.
 */
export function useUserAnalytics(days: number) {
  return useQuery<AnalyticsDashboard>({
    queryKey: ["admin", "analytics", days],
    queryFn: () => apiFetch<AnalyticsDashboard>(`${BASE}/analytics?days=${days}`),
    staleTime: 30_000,
    retry: false,
  });
}
