import { auth } from '@/auth'
import { db } from '@/lib/db'
import { sessions } from '@/lib/db/schema'
import { eq, and } from 'drizzle-orm'
import { NextRequest, NextResponse } from 'next/server'

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const authSession = await auth()
  if (!authSession?.user?.id) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { id } = await params
  const isAdmin = (authSession.user as { role?: string }).role === 'admin'

  const result = await db
    .select()
    .from(sessions)
    .where(
      isAdmin
        ? eq(sessions.id, id)
        : and(eq(sessions.id, id), eq(sessions.viewerUserId, authSession.user.id))
    )
    .limit(1)

  if (!result[0]) {
    return NextResponse.json({ error: 'Session not found' }, { status: 404 })
  }

  return NextResponse.json({ session: result[0] })
}

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const authSession = await auth()
  if (!authSession?.user?.id) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { id } = await params
  const body = await request.json()

  const updates: Record<string, unknown> = {}
  if (body.endedAt !== undefined) updates.endedAt = body.endedAt ? new Date(body.endedAt) : new Date()
  if (body.durationSeconds !== undefined) updates.durationSeconds = body.durationSeconds

  await db
    .update(sessions)
    .set(updates)
    .where(and(eq(sessions.id, id), eq(sessions.viewerUserId, authSession.user.id)))

  return NextResponse.json({ success: true })
}
