// ============================================================
// infrastructure/storage/index.ts — 本地存储模块统一入口
//
// 初始化流程：
//   await initStorage()      // AppProvider 挂载后调用一次
//   await clearUserStorage() // 退出登录时调用
//   await saveDatabase()     // 定期或退出前调用（保存到磁盘）
//
// 目录结构（自动管理）：
//   <userData>/heixiu-data/
//   ├── heixiu.db                     ← 加密的 sql.js 持久化镜像
//   └── media-cache/<userId>/<date>/   ← 媒体文件缓存
//
// 使用示例：
//   import { initStorage, getTasks, syncTasks, saveParamSnapshot } from '@/shared/infrastructure/storage';
// ============================================================

import { openDatabase, isOpen } from './core/db-core';
import { loadDatabase, saveDatabase } from './core/db-encrypt';
import { clearUserIdCache } from './services/user-scope';
import { clearUserTasks, getTaskCount as _getTaskCount } from './stores/task-store';
import { clearUserOrders, getOrderCount as _getOrderCount } from './stores/order-store';
import { clearUserParams } from './stores/param-store';
import { clearUserMedia, getMediaCount as _getMediaCount, getMediaTotalSize as _getMediaTotalSize } from './stores/media-store';
import { logger } from '@/shared/utils/bus';

// ---------- 重新导出 ----------

export { openDatabase, closeDatabase, isOpen, exportDatabase, execute, queryAll, queryOne } from './core/db-core';
export { loadDatabase, saveDatabase } from './core/db-encrypt';
export { getCurrentUserId, clearUserIdCache, getTodayKey, hashURL, formatBytes } from './services/user-scope';
export { upsertTask, syncTasks, getTasks, getTaskById, deleteTask, getTaskCount, clearUserTasks, rowToTask } from './stores/task-store';
export { upsertOrder, syncRechargeOrders, syncVipOrders, getOrders, getOrderById, deleteOrder, getOrderCount, clearUserOrders } from './stores/order-store';
export { saveParamSnapshot, fillOutputData, getParamByTaskId, getParamHistory, parseParams, deleteParamHistory, clearUserParams } from './stores/param-store';
export { upsertMediaCache, getMediaByUrl, hasMedia, getMediaCount, getMediaTotalSize, deleteMediaByUrl, clearExpiredMedia, clearUserMedia } from './stores/media-store';
export { setSetting, getSetting, getAllSettings, deleteSetting, getOutputPath, setOutputPath, getTeamRepoPath, setTeamRepoPath } from './stores/settings-store';
export { getCursor, updateCursor, hasMore, nextPage, syncedCount, totalCount, getPageSize } from './services/sync-manager';
export { writeFile, readFile, deleteFile, makeDir, showItemInFolder, fileExists, saveBlobToFile, readFileAsBlobUrl, getDataDir } from './ipc-file';
export { loadMedia, preloadMedia, isVideoMime, isImageMime, isAudioMime, revokeMediaUrl, isMediaSuccess, isMediaFailure } from './services/media-loader';
export type { MediaLoadResult, MediaLoadSuccess, MediaLoadFailure } from './services/media-loader';
export type {
  TaskRecordEntry, TaskQueryFilter,
  OrderRecordEntry, OrderType, OrderQueryFilter,
  ParamHistoryEntry, MediaCacheEntry,
  SyncCursor, SyncDataType, AppSetting,
} from './core/types';

// ---------- 初始化 ----------

/**
 * 初始化本地存储模块。
 *
 * 流程：从磁盘加载加密数据 → 解密 → sql.js 打开 → 建表
 *
 * @returns true 表示就绪
 */
export async function initStorage(): Promise<boolean> {
  // 幂等：已经打开就跳过
  if (isOpen()) {
    console.log('[storage] 数据库已打开，跳过重复初始化');
    return true;
  }

  console.log('[storage] 开始初始化...');
  // 1. 尝试从磁盘加载已有数据
  let data: Uint8Array | undefined;
  try {
    data = await loadDatabase();
    console.log(`[storage] 加载磁盘数据：${data ? `${data.byteLength} bytes` : '无（首次启动）'}`);
  } catch (err) {
    console.warn('[storage] 加载持久化数据失败，将创建新数据库', err);
    logger.warn('storage', '加载持久化数据失败，将创建新数据库', err instanceof Error ? err : undefined);
  }

  // 2. 打开数据库
  const ok = await openDatabase(data);
  if (!ok) {
    console.error('[storage] 数据库打开失败，本地存储不可用');
    logger.warn('storage', '数据库打开失败，本地存储不可用');
    return false;
  }

  // 3. 清理过期媒体缓存
  try {
    const { clearExpiredMedia } = await import('./stores/media-store');
    clearExpiredMedia();
  } catch { /* ignore */ }

  console.log('[storage] 本地存储模块初始化完成');
  logger.info('storage', '本地存储模块初始化完成');
  return true;
}

// ---------- 清理 ----------

/** 清除当前用户的所有本地数据并持久化空库到磁盘 */
export async function clearUserStorage(): Promise<void> {
  // 守卫：数据库未初始化或已被清理，无需重复操作
  if (!isOpen()) {
    logger.debug('storage', '数据库未打开，跳过 clearUserStorage');
    return;
  }

  // 1. 清空所有表数据
  try {
    await Promise.allSettled([
      Promise.resolve(clearUserTasks()),
      Promise.resolve(clearUserOrders()),
      Promise.resolve(clearUserParams()),
      Promise.resolve(clearUserMedia()),
    ]);
  } catch { /* ignore */ }

  // 2. 保存空库到磁盘（覆盖旧数据，但不关闭——以便重新登录后直接使用）
  await saveDatabase();
  clearUserIdCache();
  logger.info('storage', '用户存储数据已清理');
}

// ---------- 统计 ----------

/** 获取存储统计信息 */
export function getStorageStats() {
  return {
    taskCount: _getTaskCount(),
    orderCount: _getOrderCount(),
    mediaCount: _getMediaCount(),
    mediaSize: _getMediaTotalSize(),
    dbReady: isOpen(),
  };
}
