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

export async function GET() {
  const session = await auth()
  if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

  const result = await db
    .select({ fullName: users.fullName, company: users.company, email: users.email, role: users.role })
    .from(users)
    .where(eq(users.id, session.user.id))
    .limit(1)

  return NextResponse.json({ user: result[0] ?? null })
}

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

  const { fullName, company } = await request.json()

  await db
    .update(users)
    .set({ fullName: fullName ?? null, company: company ?? null, updatedAt: new Date() })
    .where(eq(users.id, session.user.id))

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