import { NextRequest, 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 metrics = await prisma.funnelMetric.findMany({ orderBy: { date: 'desc' }, take: 30 })
  return NextResponse.json({ metrics })
}

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

  const data = await req.json()
  const metric = await prisma.funnelMetric.create({ data: { ...data, date: new Date(data.date || new Date()) } })

  await prisma.activityLog.create({
    data: { userId: user.userId, action: 'recorded', entity: 'FunnelMetric', entityId: metric.id, details: 'New metric entry' },
  })

  return NextResponse.json({ metric })
}
