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

export async function GET(req: NextRequest) {
  const user = await getSessionFromRequest(req)
  if (!user) return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })

  const queryParams: any[] = []
  let where = 'WHERE 1=1'

  if (user.role !== 'admin_global') {
    where += ' AND s.tenant_id = ?'
    queryParams.push(user.tenant_id)
  }

  const [rows] = await pool.execute<any[]>(
    `SELECT s.*, t.name as tenant_name FROM sync_history s
     LEFT JOIN tenants t ON t.id = s.tenant_id
     ${where} ORDER BY s.started_at DESC LIMIT 100`,
    queryParams
  )
  return NextResponse.json(rows)
}

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

  const { tenant_id } = await req.json()
  const targetTenant = user.role === 'admin_global' ? tenant_id : user.tenant_id

  // Cria tarefa de sincronização para o agente
  await pool.execute(
    `INSERT INTO agent_tasks (tenant_id, type, payload, status) VALUES (?, 'full_sync', ?, 'pending')`,
    [targetTenant, JSON.stringify({ requested_by: user.email, requested_at: new Date().toISOString() })]
  )

  // Registra início da sincronização
  const [result] = await pool.execute<any>(
    `INSERT INTO sync_history (tenant_id, status, triggered_by) VALUES (?, 'running', ?)`,
    [targetTenant, user.email]
  )

  return NextResponse.json({ ok: true, sync_id: result.insertId })
}
