// ============================================================
// data-sync.ts — 数据同步辅助函数
//
// 供设置页 [加载历史数据] 和列表页 [下一页] 共用。
// 职责：
//   - 调用 API 拉取分页数据
//   - 同步到本地 sql.js 缓存
//   - 更新分页游标
//   - 返回是否还有更多数据
// ============================================================

import {
  syncTasks, syncRechargeOrders, syncVipOrders,
  hasMore, nextPage, updateCursor,
} from '@/shared/infrastructure/storage';
import { TaskAPI } from '@/modules/home/controllers/task-api';
import { PaymentAPI } from '@/modules/account/controllers/payment-api';
import { VipAPI } from '@/modules/account/controllers/vip-api';
import { logger } from '@/shared/utils/bus';

const PAGE_SIZE = 100;

// ======== 任务 ========

export async function fetchAndSyncTasks(): Promise<{ count: number; hasMore: boolean }> {
  if (!hasMore('tasks')) return { count: 0, hasMore: false };
  const page = nextPage('tasks');
  try {
    const res = await TaskAPI.getTaskList({ page, page_size: PAGE_SIZE });
    const sorted = [...res.items].sort(
      (a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime(),
    );
    syncTasks(sorted);
    updateCursor('tasks', page, res.total);
    logger.info('storage', `任务同步：第 ${page} 页，${sorted.length} 条，共 ${res.total} 条`);
    return { count: sorted.length, hasMore: page * PAGE_SIZE < res.total };
  } catch (err) {
    logger.error('storage', '任务同步失败', err instanceof Error ? err : undefined);
    throw err;
  }
}

export function hasMoreTasks(): boolean {
  return hasMore('tasks');
}

// ======== 充值订单 ========

export async function fetchAndSyncRechargeOrders(): Promise<{ count: number; hasMore: boolean }> {
  if (!hasMore('recharge_orders')) return { count: 0, hasMore: false };
  const page = nextPage('recharge_orders');
  try {
    const res = await PaymentAPI.getOrdersListInfo({ page, page_size: PAGE_SIZE });
    syncRechargeOrders(res);
    // API 未返回 total → 用返回条数推算
    const total = res.length >= PAGE_SIZE ? (page * PAGE_SIZE) + PAGE_SIZE : page * PAGE_SIZE;
    updateCursor('recharge_orders', page, total);
    logger.info('storage', `充值订单同步：第 ${page} 页，${res.length} 条`);
    return { count: res.length, hasMore: res.length >= PAGE_SIZE };
  } catch (err) {
    logger.error('storage', '充值订单同步失败', err instanceof Error ? err : undefined);
    throw err;
  }
}

export function hasMoreRechargeOrders(): boolean {
  return hasMore('recharge_orders');
}

// ======== VIP 订单 ========

export async function fetchAndSyncVipOrders(): Promise<{ count: number; hasMore: boolean }> {
  if (!hasMore('vip_orders')) return { count: 0, hasMore: false };
  const page = nextPage('vip_orders');
  try {
    const res = await VipAPI.getVipOrders({ page, page_size: PAGE_SIZE });
    syncVipOrders(res);
    const total = res.length >= PAGE_SIZE ? (page * PAGE_SIZE) + PAGE_SIZE : page * PAGE_SIZE;
    updateCursor('vip_orders', page, total);
    logger.info('storage', `VIP 订单同步：第 ${page} 页，${res.length} 条`);
    return { count: res.length, hasMore: res.length >= PAGE_SIZE };
  } catch (err) {
    logger.error('storage', 'VIP 订单同步失败', err instanceof Error ? err : undefined);
    throw err;
  }
}

export function hasMoreVipOrders(): boolean {
  return hasMore('vip_orders');
}
