import { SyncHistoryRepo } from '@/entities/sync-history';

export interface SyncResult {
  synced?: number;
  skipped?: number;
  contacts?: number;
  conversations?: number;
}

export async function withSyncHistory<T extends SyncResult>(
  deviceId: string,
  module: string,
  fn: () => Promise<T>,
): Promise<T> {
  const row = await SyncHistoryRepo.create({
    device_id: deviceId,
    module,
    started_at: new Date().toISOString(),
    status: 'pending',
  });
  const id = row.id;

  try {
    const result = await fn();
    await SyncHistoryRepo.update(id, {
      status: 'success',
      completed_at: new Date().toISOString(),
      messages_synced: result.synced ?? 0,
      contacts_synced: result.contacts ?? 0,
      conversations_synced: result.conversations ?? 0,
    });
    return result;
  } catch (err) {
    await SyncHistoryRepo.update(id, {
      status: 'error',
      completed_at: new Date().toISOString(),
      error_message: err instanceof Error ? err.message : String(err),
    });
    throw err;
  }
}
