import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { getUser } from '@/lib/auth'

export async function GET() {
  const user = await getUser()
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

  const [tiers, tasks, recentActivity, latestMetric] = await Promise.all([
    prisma.subscriptionTier.findMany({ orderBy: { tierNumber: 'asc' } }),
    prisma.launchTask.findMany({ orderBy: [{ phase: 'asc' }, { sortOrder: 'asc' }] }),
    prisma.activityLog.findMany({
      orderBy: { createdAt: 'desc' },
      take: 5,
      include: { user: { select: { name: true } } },
    }),
    prisma.funnelMetric.findFirst({ orderBy: { date: 'desc' } }),
  ])

  const totalSubscribers = tiers.reduce((sum, t) => sum + t.subscriberCount, 0)
  const mrr = tiers.reduce((sum, t) => sum + t.subscriberCount * t.price, 0)
  const totalTasks = tasks.length
  const doneTasks = tasks.filter(t => t.status === 'done').length
  const launchProgress = totalTasks > 0 ? Math.round((doneTasks / totalTasks) * 100) : 0
  const nextTasks = tasks.filter(t => t.status !== 'done').slice(0, 5)

  return NextResponse.json({
    mrr,
    totalSubscribers,
    launchProgress,
    nextTasks,
    tiers,
    recentActivity,
    latestMetric,
  })
}
