export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import getDB from '@/lib/prisma';

// GET /api/user/profile — Get current user profile with stats
export async function GET() {
    const session = await auth();
    if (!session?.user?.id) {
        return NextResponse.json({ error: 'Non autorisé' }, { status: 401 });
    }

    const prisma = getDB();
    const user = await prisma.user.findUnique({
        where: { id: session.user.id },
        include: { subscriptionPlan: true }
    } as any) as any; // Bypass Prisma type cache

    if (!user) {
        return NextResponse.json({ error: 'Utilisateur non trouvé' }, { status: 404 });
    }

    // Compute total word count from all chapters content
    const chapters = await prisma.chapter.findMany({
        where: { project: { userId: session.user.id } },
        select: { content: true },
    });

    const totalWords = chapters.reduce((total, chapter) => {
        const text = (chapter.content || '').replace(/<[^>]*>/g, ' ').trim();
        return total + (text ? text.split(/\s+/).length : 0);
    }, 0);

    const response = NextResponse.json({
        id: user.id,
        email: user.email,
        name: user.name,
        avatar: user.avatar,
        bio: user.bio,
        plan: user.planId || user.plan || 'free',
        planDetails: user.subscriptionPlan ? {
            id: user.subscriptionPlan.id,
            name: user.subscriptionPlan.name,
            displayName: user.subscriptionPlan.displayName,
            price: user.subscriptionPlan.price,
            description: user.subscriptionPlan.description,
            features: user.subscriptionPlan.features,
            maxProjects: user.subscriptionPlan.maxProjects,
            maxAiActions: user.subscriptionPlan.maxAiActions,
            isPopular: user.subscriptionPlan.isPopular
        } : undefined,
        aiActionsUsed: user.aiActionsUsed,
        dailyWordGoal: user.dailyWordGoal,
        writingStreak: user.writingStreak,
        lastWriteDate: user.lastWriteDate,
        createdAt: user.createdAt,
        totalWords,
    });
    response.headers.set('Cache-Control', 'no-store, max-age=0');
    return response;
}

// PUT /api/user/profile — Update user profile
export async function PUT(request: NextRequest) {
    const session = await auth();
    if (!session?.user?.id) {
        return NextResponse.json({ error: 'Non autorisé' }, { status: 401 });
    }

    const prisma = getDB();
    const body = await request.json();

    const data: Record<string, unknown> = {};
    if (body.name !== undefined) data.name = body.name;
    if (body.avatar !== undefined) data.avatar = body.avatar;
    if (body.bio !== undefined) data.bio = body.bio;
    if (body.dailyWordGoal !== undefined) data.dailyWordGoal = body.dailyWordGoal;
    if (body.writingStreak !== undefined) data.writingStreak = body.writingStreak;
    if (body.lastWriteDate !== undefined) data.lastWriteDate = body.lastWriteDate ? new Date(body.lastWriteDate) : null;

    const updated = await prisma.user.update({
        where: { id: session.user.id },
        data,
    });

    return NextResponse.json(updated);
}
