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

import type { SpreadsheetHistoryEntry } from '../types';

const prefix = 'spreadsheet-history/';

export interface RemoteHistoryItem {
  id: number;
  table_name: string;
  sheet_key?: string;
  admin_user_id: number;
  admin_user_name: string;
  row_key: string;
  field_id: string;
  action: string;
  before_snapshot: unknown;
  after_snapshot: unknown;
  client_entry_id?: string;
  created_at: string;
}

export async function saveHistoryBatch(
  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 listRemoteHistory(params: {
  table_name: string;
  sheet_key?: string;
  page?: number;
  pageSize?: number;
}) {
  return requestClient.get<{
    items: RemoteHistoryItem[];
    total: number;
  }>(`${prefix}list`, { params });
}

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