// ============================================================
// infrastructure/storage/media-store.ts — 媒体缓存存储
//
// 职责：
//   - 媒体缓存元数据 CRUD（Blob 实体由主进程管理）
//   - URL → local_path 映射 + LRU 淘汰
//   - 读取时更新访问时间（LRU 排序依据）
// ============================================================

import { execute, queryAll, queryOne } from '../core/db-core';
import { getCurrentUserId, getTodayKey, hashURL } from '../services/user-scope';
import type { MediaCacheEntry } from '../core/types';
import { logger } from '@/shared/utils/bus';

// ---------- API ----------

export function upsertMediaCache(
  url: string,
  mimeType: string,
  fileSize: number,
  localPath: string,
): MediaCacheEntry | null {
  const uid = getCurrentUserId();
  const urlHash = hashURL(url);
  const now = Date.now();

  // 删除旧条目（同 URL 覆盖）
  execute(`DELETE FROM media_cache WHERE url_hash = ?`, [urlHash]);

  execute(
    `INSERT INTO media_cache (user_id, url_hash, original_url, local_path, mime_type, file_size, created_date, accessed_at)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
    [uid, urlHash, url, localPath, mimeType, fileSize, getTodayKey(), now],
  );

  const row = queryOne<MediaCacheEntry>(`SELECT * FROM media_cache WHERE url_hash = ?`, [urlHash]);
  return row ?? null;
}

export function getMediaByUrl(url: string): MediaCacheEntry | null {
  const row = queryOne<MediaCacheEntry>(`SELECT * FROM media_cache WHERE url_hash = ?`, [hashURL(url)]);
  if (row) {
    // 更新访问时间（LRU）
    execute(`UPDATE media_cache SET accessed_at = ? WHERE id = ?`, [Date.now(), row.id!]);
  }
  return row;
}

export function hasMedia(url: string): boolean {
  const row = queryOne<{ cnt: number }>(`SELECT COUNT(*) as cnt FROM media_cache WHERE url_hash = ?`, [hashURL(url)]);
  return (row?.cnt ?? 0) > 0;
}

export function getMediaCount(): number {
  const row = queryOne<{ cnt: number }>(`SELECT COUNT(*) as cnt FROM media_cache WHERE user_id = ?`, [getCurrentUserId()]);
  return row?.cnt ?? 0;
}

export function getMediaTotalSize(): number {
  const row = queryOne<{ total: number }>(`SELECT COALESCE(SUM(file_size), 0) as total FROM media_cache WHERE user_id = ?`, [getCurrentUserId()]);
  return row?.total ?? 0;
}

export function deleteMediaByUrl(url: string): void {
  execute(`DELETE FROM media_cache WHERE url_hash = ?`, [hashURL(url)]);
}

export function clearExpiredMedia(maxAgeDays = 30): number {
  const cutoff = Date.now() - maxAgeDays * 86400000;
  const rows = queryAll<MediaCacheEntry>(`SELECT id, local_path FROM media_cache WHERE accessed_at < ?`, [cutoff]);
  for (const r of rows) {
    if (r.id) execute(`DELETE FROM media_cache WHERE id = ?`, [r.id]);
  }
  if (rows.length > 0) logger.info('storage', `已清理 ${rows.length} 条过期媒体缓存`);
  return rows.length;
}

export function clearUserMedia(): void {
  execute(`DELETE FROM media_cache WHERE user_id = ?`, [getCurrentUserId()]);
}
