// GFS Local Agent API - Register agent
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import { telegramConnector } from '@/lib/gfs/integrations';

export const dynamic = 'force-dynamic';

// POST /api/gfs/local-agent/register - Register a new agent connection
export async function POST(request: NextRequest) {
  const token = request.headers.get('X-Agent-Token');
  const machineId = request.headers.get('X-Machine-ID');

  if (!token) {
    return NextResponse.json({ error: 'Missing agent token' }, { status: 401 });
  }

  try {
    const crypto = await import('crypto');
    const tokenHash = crypto.createHash('sha256').update(token).digest('hex');

    // Verify token exists
    const agentToken = await prisma.localAgentToken.findUnique({
      where: { tokenHash },
    });

    if (!agentToken || !agentToken.isActive) {
      return NextResponse.json({ error: 'Invalid or inactive token' }, { status: 401 });
    }

    if (agentToken.expiresAt && agentToken.expiresAt < new Date()) {
      return NextResponse.json({ error: 'Token expired' }, { status: 401 });
    }

    const body = await request.json();

    // Update token with machine info
    await prisma.localAgentToken.update({
      where: { id: agentToken.id },
      data: {
        machineId: machineId || body.machineId,
        lastUsed: new Date(),
      },
    });

    // Notify admins of new connection
    await telegramConnector.notifyAdmins(
      'Local Agent Connected',
      `🖥️ *${agentToken.name}* is now online\n\n` +
      `Machine: \`${machineId || body.machineId || 'unknown'}\`\n` +
      `Platform: ${body.platform || 'unknown'}\n` +
      `Node: ${body.nodeVersion || 'unknown'}\n\n` +
      `Capabilities: ${(body.capabilities || []).join(', ')}`,
      'info'
    );

    return NextResponse.json({
      success: true,
      message: 'Agent registered',
      tokenName: agentToken.name,
    });
  } catch (error) {
    console.error('Agent registration error:', error);
    return NextResponse.json(
      { error: 'Registration failed' },
      { status: 500 }
    );
  }
}
