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 tiers = await prisma.subscriptionTier.findMany({ orderBy: { tierNumber: 'asc' } })
  return NextResponse.json({ tiers })
}

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

  const { id, ...data } = await req.json()
  const tier = await prisma.subscriptionTier.update({ where: { id }, data })

  await prisma.activityLog.create({
    data: { userId: user.userId, action: 'updated', entity: 'SubscriptionTier', entityId: tier.id, details: `${tier.name}: ${JSON.stringify(data)}` },
  })

  return NextResponse.json({ tier })
}
