import { ObjectId } from "mongodb";
import { getCollection } from "../mongodb";

export type ArticleType = {
    title: string;
    description: string;
    link: string;
    _id: string;
    content: string;
    priority: number;
    cover: string;
    addTime: number;
}
export async function getArticleList({ page = 1, pageSize = 9999 }: {
    page?: number;
    pageSize?: number;
}) {
    const collection = await getCollection('article');
    const startIndex = (page - 1) * pageSize;
    // 构建查询条件对象

    const pipeline = [
        // 根据构建好的查询条件筛选文档
        { $sort: { priority: 1 } },
        { $skip: startIndex },
        { $limit: pageSize },
        {
            $addFields: {
                _id: { $toString: "$_id" }
            }
        }
    ];
    const cursor = collection.aggregate<ArticleType>(pipeline);
    const list = await cursor.toArray();
    // 获取符合查询条件的文档总数
    const total = await collection.countDocuments();
    return {
        total,
        list
    }
}
export async function getArticle(id: string) {
    const collection = await getCollection('link-article');
    return collection.findOne({ _id: id as any }).then(res => res ? {
        ...res,
        _id: res._id.toString()
    } as ArticleType : null)
}