import { NextRequest, NextResponse } from 'next/server'
import { query } from '@/lib/db'
import { getSession } from '@/lib/auth'

export async function PATCH(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  const user = await getSession()
  if (!user) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const { id } = await params
  const body   = await req.json() as {
    concluida?: boolean
    descricao?: string
    vencimento?: string
    tipo?: string
  }

  // vendedor só pode editar suas próprias tarefas
  const ownerCheck = user.role === 'vendedor' ? `AND usuario_id = ${user.id}` : ''

  const sets: string[] = []
  const vals: unknown[] = []
  let p = 1

  if (body.descricao !== undefined) { sets.push(`descricao = $${p}`);  vals.push(body.descricao);  p++ }
  if (body.vencimento !== undefined){ sets.push(`vencimento = $${p}`); vals.push(body.vencimento); p++ }
  if (body.tipo !== undefined)      { sets.push(`tipo = $${p}`);       vals.push(body.tipo);       p++ }
  if (body.concluida === true) {
    sets.push(`concluida = true`, `concluida_em = NOW()`)
  } else if (body.concluida === false) {
    sets.push(`concluida = false`, `concluida_em = NULL`)
  }

  if (!sets.length) return NextResponse.json({ error: 'nothing to update' }, { status: 400 })

  vals.push(id)
  await query(
    `UPDATE crm_tarefas SET ${sets.join(', ')} WHERE id = $${p} ${ownerCheck}`,
    vals,
  )

  return NextResponse.json({ ok: true })
}

export async function DELETE(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  const user = await getSession()
  if (!user) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const { id } = await params
  const ownerCheck = user.role === 'vendedor' ? `AND usuario_id = ${user.id}` : ''

  await query(`DELETE FROM crm_tarefas WHERE id = $1 ${ownerCheck}`, [id])
  return NextResponse.json({ ok: true })
}
