import { NextRequest, NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import { query } from '@/lib/db'
import { verifyPassword, createSession } from '@/lib/auth'

export async function POST(req: NextRequest) {
  const { email, senha } = await req.json() as { email: string; senha: string }
  if (!email || !senha) {
    return NextResponse.json({ error: 'E-mail e senha obrigatórios' }, { status: 400 })
  }

  const rows = await query<{ id: number; senha_hash: string; nome: string; role: string; ativo: boolean }>(
    `SELECT id, senha_hash, nome, role, ativo FROM usuarios WHERE email = $1`,
    [email.trim().toLowerCase()],
  )
  const user = rows[0]
  if (!user || !user.ativo || !verifyPassword(senha, user.senha_hash)) {
    return NextResponse.json({ error: 'Credenciais inválidas' }, { status: 401 })
  }

  const token = await createSession(user.id)
  const jar   = await cookies()
  jar.set('session', token, {
    httpOnly: true,
    sameSite: 'lax',
    path:     '/',
    maxAge:   30 * 24 * 60 * 60,
  })

  return NextResponse.json({ id: user.id, nome: user.nome, role: user.role })
}
