/**
 * 数据变更日志 Hooks
 *
 * contract §2.4：dataChangeLogs
 */
import { useCallback, useState } from "react";
import { useGraphQuery } from "./use-graphql";
import { DATA_CHANGE_LOGS_QUERY } from "@/lib/graphql-client";
import type {
  DataChangeLogViewModel,
  PaginatedResult,
  ListFilter,
} from "@/types/view-models";

interface DataChangeLogsResponse {
  dataChangeLogs: PaginatedResult<DataChangeLogViewModel>;
}

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

export function useDataChangeLogs(filter: DataChangeLogFilter) {
  const result = useGraphQuery<DataChangeLogsResponse>(DATA_CHANGE_LOGS_QUERY, {
    filter,
  });
  return {
    ...result,
    data: result.data?.dataChangeLogs ?? null,
  };
}

export function useDataChangeLogFilter(initial?: Partial<DataChangeLogFilter>) {
  const [filter, setFilter] = useState<DataChangeLogFilter>({
    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 setTableName = useCallback(
    (tableName: string) =>
      setFilter((f) => ({ ...f, tableName: tableName || undefined, page: 1 })),
    [],
  );
  const setAction = useCallback(
    (action: string) =>
      setFilter((f) => ({ ...f, action: action || undefined, page: 1 })),
    [],
  );
  return { filter, setFilter, setPage, setSearch, setTableName, setAction };
}

/** 数据变更日志导出 CSV */
export function exportDataChangeLogsCsv(logs: DataChangeLogViewModel[]): void {
  const headers = [
    "时间",
    "操作人",
    "数据表",
    "操作",
    "记录ID",
    "变更前",
    "变更后",
    "IP",
  ];
  const rows = logs.map((l) => [
    new Date(l.occurredAt).toLocaleString("zh-CN"),
    l.actorName,
    l.tableName,
    l.action,
    l.recordId,
    l.beforeState ?? "",
    l.afterState ?? "",
    l.ip,
  ]);
  const csv = [headers, ...rows]
    .map((row) =>
      row.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(","),
    )
    .join("\n");
  const blob = new Blob([`\uFEFF${csv}`], { type: "text/csv;charset=utf-8;" });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = `data-change-logs-${new Date().toISOString().slice(0, 10)}.csv`;
  link.click();
  URL.revokeObjectURL(url);
}
