import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
import { getSessionFromRequest } from '@/lib/session'

export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const user = await getSessionFromRequest(req)
  if (!user) return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })

  const { id } = await params
  const { new_password, must_change } = await req.json()

  if (!new_password) return NextResponse.json({ error: 'Nova senha obrigatória' }, { status: 400 })

  const [userRows] = await pool.execute<any[]>('SELECT tenant_id, sam_account FROM ad_users WHERE id = ?', [id])
  if (!userRows[0]) return NextResponse.json({ error: 'Usuário não encontrado' }, { status: 404 })

  await pool.execute(
    `INSERT INTO agent_tasks (tenant_id, type, payload, status) VALUES (?, 'reset_password', ?, 'pending')`,
    [userRows[0].tenant_id, JSON.stringify({ ad_user_id: id, sam_account: userRows[0].sam_account, new_password, must_change: !!must_change })]
  )

  await pool.execute("UPDATE ad_users SET sync_status = 'pending' WHERE id = ?", [id])

  return NextResponse.json({ ok: true })
}
