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 tasks = await prisma.launchTask.findMany({ orderBy: [{ phase: 'asc' }, { sortOrder: 'asc' }] })
  return NextResponse.json({ tasks })
}

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 task = await prisma.launchTask.create({ data })

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

  return NextResponse.json({ task })
}

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 task = await prisma.launchTask.update({ where: { id }, data })

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

  return NextResponse.json({ task })
}
