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

export async function GET(request: NextRequest) {
  try {
    // Get the first clinic (for demo purposes)
    const clinic = await prisma.clinic.findFirst();
    if (!clinic) {
      return NextResponse.json({ error: 'No clinic found' }, { status: 404 });
    }

    // Get tree counts
    const totalTrees = await prisma.reminderTree.count({
      where: { clinicId: clinic.id }
    });

    const activeTrees = await prisma.reminderTree.count({
      where: { clinicId: clinic.id, isActive: true }
    });

    // Get journey counts
    const totalJourneys = await prisma.userJourney.count({
      where: { 
        appointment: { clinicId: clinic.id }
      }
    });

    const activeJourneys = await prisma.userJourney.count({
      where: { 
        appointment: { clinicId: clinic.id },
        status: 'active'
      }
    });

    // Get messages this week
    const oneWeekAgo = new Date();
    oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);

    const messagesThisWeek = await prisma.messageLog.count({
      where: {
        clinicId: clinic.id,
        direction: 'outgoing',
        sentAt: { gte: oneWeekAgo }
      }
    });

    // Get average engagement score
    const profiles = await prisma.patientProfile.findMany({
      where: { clinicId: clinic.id },
      select: { engagementScore: true }
    });

    const avgEngagementScore = profiles.length > 0
      ? profiles.reduce((sum, p) => sum + p.engagementScore, 0) / profiles.length
      : 0;

    // Get top performing tree (by completion rate)
    const treesWithStats = await prisma.reminderTree.findMany({
      where: { clinicId: clinic.id },
      include: {
        _count: {
          select: { userJourneys: true }
        }
      }
    });

    let topPerformingTree = null;
    let bestCompletionRate = 0;

    for (const tree of treesWithStats) {
      if (tree._count.userJourneys > 0) {
        const completedJourneys = await prisma.userJourney.count({
          where: {
            treeId: tree.id,
            status: 'completed'
          }
        });

        const completionRate = (completedJourneys / tree._count.userJourneys) * 100;

        if (completionRate > bestCompletionRate) {
          bestCompletionRate = completionRate;
          topPerformingTree = {
            name: tree.name,
            completionRate
          };
        }
      }
    }

    const stats = {
      totalTrees,
      activeTrees,
      totalJourneys,
      activeJourneys,
      messagesThisWeek,
      avgEngagementScore,
      topPerformingTree
    };

    return NextResponse.json(stats);
  } catch (error) {
    console.error('Failed to fetch tree stats:', error);
    return NextResponse.json(
      { error: 'Failed to fetch tree stats' }, 
      { status: 500 }
    );
  }
}