// GFS Local Agent API - Get pending commands
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';

export const dynamic = 'force-dynamic';

// Validate agent token
async function validateToken(request: NextRequest): Promise<{ valid: boolean; tokenId?: string }> {
  const token = request.headers.get('X-Agent-Token');
  const machineId = request.headers.get('X-Machine-ID');

  if (!token) {
    return { valid: false };
  }

  try {
    // Hash the token to compare with stored hash
    const crypto = await import('crypto');
    const tokenHash = crypto.createHash('sha256').update(token).digest('hex');

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

    if (!agentToken || !agentToken.isActive) {
      return { valid: false };
    }

    // Check expiration
    if (agentToken.expiresAt && agentToken.expiresAt < new Date()) {
      return { valid: false };
    }

    // Update last used
    await prisma.localAgentToken.update({
      where: { id: agentToken.id },
      data: { 
        lastUsed: new Date(),
        machineId: machineId || agentToken.machineId,
      },
    });

    return { valid: true, tokenId: agentToken.id };
  } catch (error) {
    console.error('Token validation error:', error);
    return { valid: false };
  }
}

// GET /api/gfs/local-agent/commands - Get pending commands for this agent
export async function GET(request: NextRequest) {
  const validation = await validateToken(request);
  if (!validation.valid) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    // Get pending commands for local_agent source
    const commands = await prisma.commandQueue.findMany({
      where: {
        status: 'pending',
        source: 'local_agent',
      },
      orderBy: [
        { priority: 'desc' },
        { createdAt: 'asc' },
      ],
      take: 10,
    });

    // Mark as processing
    if (commands.length > 0) {
      await prisma.commandQueue.updateMany({
        where: {
          id: { in: commands.map((c: any) => c.id) },
        },
        data: {
          status: 'processing',
          processedAt: new Date(),
        },
      });
    }

    return NextResponse.json({
      success: true,
      commands: commands.map((c: any) => ({
        id: c.id,
        command: c.command,
        args: c.args,
        priority: c.priority,
      })),
    });
  } catch (error) {
    console.error('Get commands error:', error);
    return NextResponse.json(
      { error: 'Failed to get commands' },
      { status: 500 }
    );
  }
}
