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

export const dynamic = 'force-dynamic';

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

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

  try {
    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 };
    }

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

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

// POST /api/gfs/local-agent/result - Report command execution result
export async function POST(request: NextRequest) {
  const validation = await validateToken(request);
  if (!validation.valid) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const body = await request.json();
    const { commandId, result } = body;

    if (!commandId || result === undefined) {
      return NextResponse.json(
        { error: 'Missing commandId or result' },
        { status: 400 }
      );
    }

    // Update command with result
    const command = await prisma.commandQueue.update({
      where: { id: commandId },
      data: {
        status: result.success ? 'completed' : 'failed',
        result: result,
        error: result.error || null,
        completedAt: new Date(),
      },
    });

    // If this command came from Telegram, notify the user
    if (command.source === 'telegram' && command.sourceId) {
      const chatId = command.sourceId;
      const emoji = result.success ? '✅' : '❌';
      const statusText = result.success ? 'Completed' : 'Failed';

      let message = `${emoji} *Command ${statusText}*\n\n`;
      message += `└ \`${command.command}\`\n\n`;

      if (result.message) {
        message += `${result.message}\n\n`;
      }

      if (result.error) {
        message += `Error: ${result.error}\n`;
      }

      if (result.stdout) {
        const output = result.stdout.slice(0, 500);
        message += `\`\`\`\n${output}${result.stdout.length > 500 ? '...' : ''}\n\`\`\``;
      }

      await telegramConnector.sendToAdmin(chatId, message);
    }

    return NextResponse.json({
      success: true,
      message: 'Result recorded',
    });
  } catch (error) {
    console.error('Report result error:', error);
    return NextResponse.json(
      { error: 'Failed to report result' },
      { status: 500 }
    );
  }
}
