import { prisma } from '@/lib/db';
import { guardMessage, guardStatus, requireOwnedProject } from '@/lib/guards';
import { createLogger } from '@/lib/logger';
import { NextRequest } from 'next/server';
const logger = createLogger({
    type: 'request:project-dictionaries',
}, {
    json: false,// 开启json格式输出
    pretty: false, // 关闭开发环境美化输出
    colors: true, // 仅当json：false时启用颜色输出可用
    includeCaller: false, // 日志不包含调用者
});
export async function GET(
    req: NextRequest,
    context: { params: Promise<{ id: string }> } // ✅ 正确：params 是 Promise
) {
    try {
        const { id: projectId } = await context.params;
        await requireOwnedProject(projectId);

        // 获取项目关联的词典
        const projectDictionaries = await prisma.projectDictionary.findMany({
            where: { projectId },
            include: {
                dictionary: {
                    include: {
                        projectBindings: {
                            select: { projectId: true },
                        },
                        entries: {
                            select: { id: true },
                        },
                    },
                },
            },
        });

        // 格式化响应数据
        const dictionaries = projectDictionaries.map((binding: any) => {
            const dict = binding.dictionary;
            const isShared = dict.projectBindings.length > 1;

            return {
                id: dict.id,
                name: dict.name,
                description: dict.description,
                visibility: dict.visibility,
                entryCount: dict.entries.length,
                isShared,
                isAutoGenerated: dict.name.includes('术语清单'),
                createdAt: dict.createdAt,
                updatedAt: dict.updatedAt,
            };
        });

        return Response.json(dictionaries);
    } catch (error) {
        logger.error('获取项目词典失败:', error);
        return Response.json(
            { error: guardMessage(error) || '获取失败' },
            { status: guardStatus(error) }
        );
    }
}
