import { NextRequest, NextResponse } from 'next/server'
import { query } from '@/lib/db'
import { getSession, hashPassword } from '@/lib/auth'

// ── GET /api/usuarios ─────────────────────────────────────────────────────────
export async function GET() {
  const user = await getSession()
  if (!user) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
  if (user.role !== 'gestor') return NextResponse.json({ error: 'forbidden' }, { status: 403 })

  const rows = await query(
    `SELECT id, nome, email, role, ativo, criado_em FROM usuarios ORDER BY nome`,
  )
  return NextResponse.json(rows)
}

// ── POST /api/usuarios ────────────────────────────────────────────────────────
export async function POST(req: NextRequest) {
  const user = await getSession()
  if (!user) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
  if (user.role !== 'gestor') return NextResponse.json({ error: 'forbidden' }, { status: 403 })

  const body = await req.json() as { nome: string; email: string; senha: string; role: string }
  if (!body.nome || !body.email || !body.senha || body.senha.length < 6) {
    return NextResponse.json({ error: 'nome, email e senha (≥6 chars) obrigatórios' }, { status: 400 })
  }

  const hash = hashPassword(body.senha)
  const role = body.role === 'gestor' ? 'gestor' : 'vendedor'

  try {
    const [row] = await query<{ id: number }>(
      `INSERT INTO usuarios (nome, email, senha_hash, role) VALUES ($1, $2, $3, $4) RETURNING id`,
      [body.nome.trim(), body.email.trim().toLowerCase(), hash, role],
    )
    return NextResponse.json({ id: row.id, ok: true })
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : String(err)
    if (msg.includes('unique')) return NextResponse.json({ error: 'E-mail já cadastrado' }, { status: 409 })
    return NextResponse.json({ error: msg }, { status: 500 })
  }
}

// ── PATCH /api/usuarios ───────────────────────────────────────────────────────
export async function PATCH(req: NextRequest) {
  const user = await getSession()
  if (!user) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
  if (user.role !== 'gestor') return NextResponse.json({ error: 'forbidden' }, { status: 403 })

  const body = await req.json() as { id: number; ativo?: boolean; role?: string; senha?: string }
  if (!body.id) return NextResponse.json({ error: 'id obrigatório' }, { status: 400 })

  const sets: string[] = []
  const vals: unknown[] = []
  let p = 1

  if (body.ativo !== undefined)  { sets.push(`ativo = $${p}`); vals.push(body.ativo); p++ }
  if (body.role)                 { sets.push(`role  = $${p}`); vals.push(body.role === 'gestor' ? 'gestor' : 'vendedor'); p++ }
  if (body.senha && body.senha.length >= 6) { sets.push(`senha_hash = $${p}`); vals.push(hashPassword(body.senha)); p++ }

  if (!sets.length) return NextResponse.json({ error: 'nothing to update' }, { status: 400 })
  vals.push(body.id)
  await query(`UPDATE usuarios SET ${sets.join(', ')} WHERE id = $${p}`, vals)
  return NextResponse.json({ ok: true })
}
