/**
 * 登录日志 Hooks
 *
 * contract §2.4：loginLogs
 */
import { useCallback, useState } from "react";
import { useGraphQuery } from "./use-graphql";
import { LOGIN_LOGS_QUERY } from "@/lib/graphql-client";
import type {
  LoginLogViewModel,
  PaginatedResult,
  ListFilter,
} from "@/types/view-models";

interface LoginLogsResponse {
  loginLogs: PaginatedResult<LoginLogViewModel>;
}

interface LoginLogFilter extends Partial<ListFilter> {
  action?: string;
  status?: string;
  startDate?: number;
  endDate?: number;
}

export function useLoginLogs(filter: LoginLogFilter) {
  const result = useGraphQuery<LoginLogsResponse>(LOGIN_LOGS_QUERY, {
    filter,
  });
  return {
    ...result,
    data: result.data?.loginLogs ?? null,
  };
}

export function useLoginLogFilter(initial?: Partial<LoginLogFilter>) {
  const [filter, setFilter] = useState<LoginLogFilter>({
    page: 1,
    pageSize: 20,
    ...initial,
  });
  const setPage = useCallback(
    (page: number) => setFilter((f) => ({ ...f, page })),
    [],
  );
  const setSearch = useCallback(
    (search: string) => setFilter((f) => ({ ...f, search, page: 1 })),
    [],
  );
  const setAction = useCallback(
    (action: string) =>
      setFilter((f) => ({ ...f, action: action || undefined, page: 1 })),
    [],
  );
  const setStatus = useCallback(
    (status: string) =>
      setFilter((f) => ({ ...f, status: status || undefined, page: 1 })),
    [],
  );
  return { filter, setFilter, setPage, setSearch, setAction, setStatus };
}
