"use server";

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

export type Link = {
    name: string;
    link?: string;
    description: string;
    _id: string;
    type: string;
    priority: number;
    articleId?: string;
    logoLink: string;
    isHot?: boolean;
    addTime: number;
    subLinkType?: string[];

}

export async function getLinkListAll() {
    const linkCollection = await getCollection('link');

    const list = await linkCollection.aggregate<Link>([
        {
            '$addFields': {
                '_id': {
                    '$toString': "$_id"
                }
            }
        },
        {
            '$lookup': {
                'from': 'link-article',
                'localField': '_id',
                'foreignField': '_id',
                'as': 'article'
            }
        }, {
            '$addFields': {
                'articleId': {
                    '$toString':
                    {
                        '$arrayElemAt': [
                            '$article._id', 0
                        ]
                    }
                }

            }
        }, {
            '$project': {
                'article': 0
            }
        }
    ]).toArray();
    console.log(list);

    return list;
}
function buildDynamicQuery(filter: Partial<Link>) {
    const query: Record<string, any> = {};

    // 遍历所有有效字段
    for (const [key, value] of Object.entries(filter)) {
        if (value === undefined) continue;

        // 特殊处理 _id 字段(ObjectId 转换)
        if (key === '_id' && typeof value === 'string') {
            query[key] = new ObjectId(value);
        }
        // 处理其他字段的精确匹配
        else {
            query[key] = value;
        }
    }
    return query;
}

// Link 类型定义
export async function getLinkList({ page = 1, pageSize = 9999, filter = {} }: {
    page?: number;
    pageSize?: number;
    filter?: Partial<Link>;
}) {
    const collection = await getCollection('link');
    const startIndex = (page - 1) * pageSize;
    // 构建查询条件对象
    let query = {} as any
    if (filter.name) {
        query.name = { $regex: filter.name, $options: 'i' };

    }
    if (filter.articleId) {
        query.articleId = filter.articleId;
    }
    if (filter.type) {
        query.type = filter.type;
    }
    const pipeline = [
        // 根据构建好的查询条件筛选文档
        {
            $match: query
        },
        { $sort: { priority: 1, _id: -1 } },
        { $skip: startIndex },
        { $limit: pageSize },
        {
            $addFields: {
                _id: { $toString: "$_id" }
            }
        }
    ];
    const cursor = collection.aggregate<Link>(pipeline);

    const list = await cursor.toArray();
    // 获取符合查询条件的文档总数
    const total = await collection.countDocuments(query);
    return {
        total,
        list
    }
}
export async function updateLink(id: string, link: Partial<Link>) {

    const collection = await getCollection('link');

    collection.updateOne({
        _id: new ObjectId(id)
    }, {
        $set: link
    })

}