/**
 * PostManager - 帖子管理核心模块（重构版�?
 *
 * 使用 Zustand store 进行状态管�?
 * 保持与旧 API 的向后兼�?
 */

import type { Post } from '../../types';
import { postService } from '@/services/post';
import { usePostManagerStore } from './postStore';
import { createCacheEntry, isCacheExpired, DEFAULT_TTL } from '../utils/cache';
import { createDedupe } from '../utils/requestDedupe';
import {
  IPostListPagedSource,
  PostListTab,
  createRemotePostListSource,
  RemotePostListSourceKind,
  POST_LIST_PAGE_SIZE,
} from './sources';

function buildListKey(type: string, page: number, pageSize: number): string {
  return `list:${type}:${page}:${pageSize}`;
}

const dedupe = createDedupe(() => usePostManagerStore);

// ==================== PostManager �?====================

class PostManager {
  // ==================== 列表相关 ====================

  /**
   * 获取帖子列表（传统分页模式）
   */
  async getPosts(
    type: PostListTab = 'hot',
    page = 1,
    pageSize = POST_LIST_PAGE_SIZE,
    forceRefresh = false
  ): Promise<Post[]> {
    const key = buildListKey(type, page, pageSize);
    const store = usePostManagerStore.getState();
    const entry = store.listsMap.get(key);

    // 检查有效缓�?
    if (!forceRefresh && entry && !isCacheExpired(entry)) {
      return entry.data;
    }

    // 过期缓存：后台刷新，立即返回旧数�?
    if (!forceRefresh && entry && isCacheExpired(entry)) {
      this.refreshPostsInBackground(key, type, page, pageSize);
      return entry.data;
    }

    // 无缓存：发起请求
    return dedupe(`posts:${key}`, async () => {
      const store = usePostManagerStore.getState();
      const response = await postService.getPosts(page, pageSize, type);
      const posts = response.list || [];
      store.setPostsList(type, page, pageSize, posts);
      return posts;
    });
  }

  private refreshPostsInBackground(
    key: string,
    type: PostListTab,
    page: number,
    pageSize: number
  ): void {
    dedupe(`posts:bg:${key}`, async () => {
      const store = usePostManagerStore.getState();
      const response = await postService.getPosts(page, pageSize, type);
      const posts = response.list || [];
      store.setPostsList(type, page, pageSize, posts);
      return posts;
    }).catch((error) => {
      console.error('[PostManager] refreshPostsInBackground error:', error);
    });
  }

  /**
   * 创建帖子列表数据源（用于 Sources 模式�?
   */
  createPostListSource(
    options: { tab?: PostListTab; channelId?: string; pageSize?: number } = {},
    kind: RemotePostListSourceKind = 'cursor'
  ): IPostListPagedSource {
    return createRemotePostListSource(kind, options);
  }

  // ==================== 详情相关 ====================

  /**
   * 获取帖子详情
   */
  async getPostDetail(postId: string, forceRefresh = false): Promise<Post | null> {
    const store = usePostManagerStore.getState();
    const entry = store.detailsMap.get(postId);

    // 有效缓存
    if (!forceRefresh && entry && !isCacheExpired(entry)) {
      return entry.data;
    }

    // 过期缓存：后台刷�?
    if (!forceRefresh && entry && isCacheExpired(entry) && entry.data) {
      this.refreshPostDetailInBackground(postId);
      return entry.data;
    }

    // 无缓存：发起请求
    return dedupe(`posts:detail:${postId}`, async () => {
      const store = usePostManagerStore.getState();
      const post = await postService.getPost(postId);
      store.setPostDetail(postId, post);
      return post;
    });
  }

  private refreshPostDetailInBackground(postId: string): void {
    dedupe(`posts:detail:bg:${postId}`, async () => {
      const store = usePostManagerStore.getState();
      const post = await postService.getPost(postId);
      store.setPostDetail(postId, post);
      return post;
    }).catch((error) => {
      console.error('[PostManager] refreshPostDetailInBackground error:', error);
    });
  }

  // ==================== 缓存管理 ====================

  /**
   * 使缓存失�?
   */
  invalidate(postId?: string): void {
    if (postId) {
      usePostManagerStore.getState().invalidateDetail(postId);
      return;
    }
    usePostManagerStore.getState().invalidateAll();
  }

  /**
   * 清除所有数�?
   */
  clear(): void {
    usePostManagerStore.getState().reset();
  }
}

export const postManager = new PostManager();

export { PostManager };

export default postManager;
