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 { searchParams } = req.nextUrl
  const page = Math.max(1, Number(searchParams.get('page') ?? 1))
  const limit = Math.min(100, Number(searchParams.get('limit') ?? 50))
  const offset = (page - 1) * limit
  const search = searchParams.get('search') ?? ''
  const action = searchParams.get('action') ?? ''
  const tenantId = searchParams.get('tenant_id') ?? ''
  const from = searchParams.get('from') ?? ''
  const to = searchParams.get('to') ?? ''

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

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

  if (search) {
    where += ' AND (a.user_name LIKE ? OR a.object_name LIKE ? OR a.action LIKE ? OR a.details LIKE ?)'
    queryParams.push(`%${search}%`, `%${search}%`, `%${search}%`, `%${search}%`)
  }
  if (action) { where += ' AND a.action = ?'; queryParams.push(action) }
  if (from) { where += ' AND a.created_at >= ?'; queryParams.push(from) }
  if (to) { where += ' AND a.created_at <= ?'; queryParams.push(to + ' 23:59:59') }

  const [countRows] = await pool.execute<any[]>(
    `SELECT COUNT(*) as total FROM audit_logs a ${where}`,
    queryParams
  )
  const total = countRows[0].total

  const [rows] = await pool.execute<any[]>(
    `SELECT a.*, t.name as tenant_name FROM audit_logs a
     LEFT JOIN tenants t ON t.id = a.tenant_id
     ${where} ORDER BY a.created_at DESC LIMIT ? OFFSET ?`,
    [...queryParams, limit, offset]
  )

  return NextResponse.json({ data: rows, total, page, limit })
}

export async function POST(req: NextRequest) {
  // Endpoint interno: aceita autenticação via sessão de portal OU agent_token no header
  const agentToken = req.headers.get('x-agent-token')
  let authorizedTenantId: string | null = null

  if (agentToken) {
    const [rows] = await pool.execute<any[]>(
      "SELECT id FROM tenants WHERE agent_token = ? AND status = 'active' LIMIT 1",
      [agentToken],
    )
    if (!rows[0]) return NextResponse.json({ error: 'Token inválido' }, { status: 401 })
    authorizedTenantId = rows[0].id
  } else {
    const user = await getSessionFromRequest(req)
    if (!user) return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })
    authorizedTenantId = (user as any).tenant_id ?? (user as any).tenantId ?? null
  }

  const body = await req.json()
  const { tenant_id, action, user_name, object_name, object_type, details, ip_address } = body

  // tenant_admin só pode registrar logs do próprio tenant
  const effectiveTenantId = authorizedTenantId ?? tenant_id
  if (!effectiveTenantId) return NextResponse.json({ error: 'tenant_id obrigatório' }, { status: 400 })

  await pool.execute(
    `INSERT INTO audit_logs (tenant_id, action, user_name, object_type, object_name, details, ip_address)
     VALUES (?, ?, ?, ?, ?, ?, ?)`,
    [effectiveTenantId, action, user_name ?? null, object_type ?? null, object_name ?? null,
     details ? JSON.stringify(details) : null, ip_address ?? null]
  )
  return NextResponse.json({ ok: true })
}
