import { useUserStore } from '@vben/stores';

import type { SpreadsheetHistoryEntry } from '../types';
import {
  appendLocalHistory,
  listUnsyncedHistory,
  markHistorySynced,
} from '../history/localHistoryStore';
import { saveHistoryBatch } from '../history/remoteHistoryApi';

let syncTimer: ReturnType<typeof setTimeout> | null = null;

function uuid() {
  return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
}

export function useEditHistory(
  tableName: string,
  sheetKey?: string,
  enabled = true,
) {
  const userStore = useUserStore();

  async function recordChange(
    payload: Omit<
      SpreadsheetHistoryEntry,
      'id' | 'tableName' | 'sheetKey' | 'userId' | 'userName' | 'synced' | 'createdAt'
    >,
  ) {
    if (!enabled) return;

    const entry: SpreadsheetHistoryEntry = {
      id: uuid(),
      tableName,
      sheetKey,
      userId: Number(userStore.userInfo?.userId ?? 0),
      userName: String(
        userStore.userInfo?.nick_name ??
          userStore.userInfo?.username ??
          '未知用户',
      ),
      createdAt: new Date().toISOString(),
      synced: false,
      ...payload,
    };

    await appendLocalHistory(entry);
    scheduleSync();
    return entry;
  }

  function scheduleSync() {
    if (syncTimer) clearTimeout(syncTimer);
    syncTimer = setTimeout(async () => {
      try {
        const pending = await listUnsyncedHistory();
        if (!pending.length) return;
        const res = await saveHistoryBatch(pending);
        await markHistorySynced(res.saved_ids ?? pending.map((p) => p.id));
      } catch {
        // retry on next change
      }
    }, 2000);
  }

  return { recordChange, scheduleSync };
}
