import { NextRequest, NextResponse } from 'next/server'
import { query } from '@/lib/db'
import { getSession } from '@/lib/auth'

// ── GET /api/tarefas ──────────────────────────────────────────────────────────
export async function GET(req: NextRequest) {
  const user = await getSession()
  if (!user) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const sp         = req.nextUrl.searchParams
  const concluida  = sp.get('concluida') // 'true' | 'false' | null (all)
  const vencimento = sp.get('vencimento') // 'pendentes' = vencimento <= hoje
  const cnpj       = sp.get('cnpj')

  const conditions: string[] = []
  const params: unknown[]    = []
  let p = 1

  // Controle de acesso: vendedor só vê suas tarefas
  if (user.role === 'vendedor') {
    conditions.push(`t.usuario_id = $${p}`)
    params.push(user.id); p++
  }

  if (concluida === 'true')  conditions.push(`t.concluida = true`)
  if (concluida === 'false') conditions.push(`t.concluida = false`)
  if (vencimento === 'pendentes') {
    conditions.push(`t.concluida = false AND t.vencimento <= CURRENT_DATE`)
  }
  if (cnpj) { conditions.push(`t.cnpj = $${p}`); params.push(cnpj); p++ }

  const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : ''

  const rows = await query(
    `SELECT
       t.id, t.cnpj, t.tipo, t.descricao, t.vencimento, t.concluida, t.concluida_em, t.criada_em,
       u.nome AS usuario_nome,
       e.razao_social, e.nome_fantasia, e.municipio, e.uf,
       COALESCE(cl.stage, 'novo') AS stage
     FROM crm_tarefas t
     JOIN usuarios u ON u.id = t.usuario_id
     LEFT JOIN empresas_monitoradas e ON e.cnpj = t.cnpj
     LEFT JOIN crm_leads cl ON cl.cnpj = t.cnpj
     ${where}
     ORDER BY t.concluida ASC, t.vencimento ASC, t.criada_em DESC`,
    params,
  )

  return NextResponse.json(rows)
}

// ── POST /api/tarefas ─────────────────────────────────────────────────────────
export async function POST(req: NextRequest) {
  const user = await getSession()
  if (!user) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const body = await req.json() as {
    cnpj?: string
    tipo?: string
    descricao?: string
    vencimento: string
    usuario_id?: number
  }

  if (!body.vencimento) {
    return NextResponse.json({ error: 'Vencimento obrigatório' }, { status: 400 })
  }

  // Gestor pode criar tarefa para outro usuário; vendedor só para si
  const targetUserId = (user.role === 'gestor' && body.usuario_id) ? body.usuario_id : user.id

  const [row] = await query<{ id: number }>(
    `INSERT INTO crm_tarefas (cnpj, usuario_id, tipo, descricao, vencimento)
     VALUES ($1, $2, $3, $4, $5)
     RETURNING id`,
    [
      body.cnpj      || null,
      targetUserId,
      body.tipo      || 'followup',
      body.descricao || null,
      body.vencimento,
    ],
  )

  return NextResponse.json({ id: row.id, ok: true })
}
