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

        await requireWritableProject(projectId);
        const project = await prisma.project.findUniqueOrThrow({
            where: { id: projectId },
            include: {
                projectDictionaries: {
                    include: {
                        dictionary: {
                            include: {
                                projectBindings: true,
                            },
                        },
                    },
                },
            },
        });

        // 执行删除
        await prisma.$transaction(async (tx: Prisma.TransactionClient) => {
            // 1. 处理词典删除（如果用户选择）
            if (deleteDictionaries) {
                for (const binding of project.projectDictionaries) {
                    const dict = binding.dictionary;
                    const isShared = dict.projectBindings.length > 1;
                    const isAutoGenerated = dict.name.includes('术语清单');

                    // 只删除专属的、自动生成的、未被共享的词典
                    if (!isShared && isAutoGenerated) {
                        await tx.dictionary.delete({
                            where: { id: dict.id },
                        });
                    }
                }
            }

            // 2. 删除绑定关系
            await tx.projectDictionary.deleteMany({ where: { projectId } });
            await tx.projectMemory.deleteMany({ where: { projectId } });

            // 3. 删除项目
            await tx.project.delete({ where: { id: projectId } });
        });

        return Response.json({
            success: true,
            message: deleteDictionaries ? '项目及专属词典已删除' : '项目已删除，词典保留',
        });
    } catch (error) {
        logger.error('删除项目失败:', error);
        return Response.json(
            { error: guardMessage(error) || '删除失败' },
            { status: guardStatus(error) }
        );
    }
}
