// src/app/api/auth/login/route.ts
import { NextResponse } from "next/server"
import bcrypt from "bcrypt"
import { getSession } from "@/server/session"
import { UserRole } from "@prisma/client"
import { prisma } from "@/server/db"
import { getClientesForContato, getContatoByEmail } from "@/server/portal-auth"

function isClientRole(role: UserRole) {
  return role === "CLIENT_ADMIN" || role === "CLIENT_VIEWER"
}

export async function POST(req: Request) {
  const body = await req.json().catch(() => null)
  const email = String(body?.email ?? "").trim().toLowerCase()
  const password = String(body?.password ?? "")

  if (!email || !password) {
    return NextResponse.json({ error: "Informe e-mail e senha." }, { status: 400 })
  }

  const contato = await getContatoByEmail(email)
  const portalPasswordOk = contato ? await bcrypt.compare(password, contato.senha) : false

  if (contato && portalPasswordOk) {
      const clients = await getClientesForContato(contato.id)
      if (clients.length) {
        const session = await getSession()

        if (clients.length === 1) {
          const client = clients[0]
          session.user = {
            id: `portal:${contato.id}`,
            email: contato.email,
            name: contato.nome ?? null,
            role: UserRole.CLIENT_VIEWER,
            tenantId: null,
            cnpj: client.cnpj ?? null,
          }
          session.portalPending = undefined
          await session.save()
          return NextResponse.json({ ok: true })
        }

        session.portalPending = {
          contatoId: contato.id,
          email: contato.email,
          name: contato.nome ?? null,
          clients,
        }
        session.user = undefined
        await session.save()

        return NextResponse.json({
          ok: false,
          needsClientSelection: true,
          clients: clients.map((c) => ({
            id: c.id,
            razao_social: c.razao_social,
            nome_fantasia: c.nome_fantasia,
            cnpj: c.cnpj,
          })),
        })
      }
  }

  const local = await prisma.user.findUnique({
    where: { email },
    select: { id: true, email: true, name: true, role: true, tenantId: true, cnpj: true, password: true },
  })

  if (local && !isClientRole(local.role)) {
    const localPasswordOk = await bcrypt.compare(password, local.password)
    if (localPasswordOk) {
      const session = await getSession()
      session.user = {
        id: local.id,
        email: local.email,
        name: local.name,
        role: local.role,
        tenantId: local.tenantId,
        cnpj: local.cnpj ?? null,
      }
      session.portalPending = undefined
      await session.save()
      return NextResponse.json({ ok: true })
    }
  }

  if (contato && portalPasswordOk) {
    return NextResponse.json({ error: "Usuário sem acesso ao portal." }, { status: 403 })
  }

  return NextResponse.json({ error: "Credenciais inválidas." }, { status: 401 })
}
