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 sessions = await prisma.contentSession.findMany({ orderBy: [{ weekStart: 'desc' }, { dayOfWeek: 'asc' }] })
  return NextResponse.json({ sessions })
}

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 session = await prisma.contentSession.create({ data: { ...data, weekStart: new Date(data.weekStart) } })

  await prisma.activityLog.create({
    data: { userId: user.userId, action: 'created', entity: 'ContentSession', entityId: session.id, details: session.title },
  })

  return NextResponse.json({ session })
}

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()
  if (data.weekStart) data.weekStart = new Date(data.weekStart)
  const session = await prisma.contentSession.update({ where: { id }, data })

  await prisma.activityLog.create({
    data: { userId: user.userId, action: 'updated', entity: 'ContentSession', entityId: session.id, details: `${session.title} → ${data.status || 'edited'}` },
  })

  return NextResponse.json({ session })
}
