import { requestClient } from '#/api/request';

import type { SpreadsheetHistoryEntry } from '#/components/canvas-spreadsheet/types';

const prefix = 'spreadsheet-history/';

export async function saveSpreadsheetHistoryBatch(
  entries: SpreadsheetHistoryEntry[],
) {
  return requestClient.post<{ saved_ids: string[] }>(`${prefix}save-batch`, {
    entries: entries.map((e) => ({
      client_entry_id: e.id,
      table_name: e.tableName,
      sheet_key: e.sheetKey,
      row_key: String(e.rowKey),
      field_id: e.fieldId,
      action: e.action,
      before_snapshot: e.beforeSnapshot,
      after_snapshot: e.afterSnapshot,
      created_at: e.createdAt,
    })),
  });
}

export async function listSpreadsheetHistory(params: {
  table_name: string;
  sheet_key?: string;
  page?: number;
  pageSize?: number;
}) {
  return requestClient.get<{ items: any[]; total: number }>(`${prefix}list`, {
    params,
  });
}

export async function rollbackSpreadsheetHistory(id: number) {
  return requestClient.post<{ success: boolean }>(`${prefix}rollback`, { id });
}
