// GFS Local Agent API - Generate agent token
import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import crypto from 'crypto';

export const dynamic = 'force-dynamic';

// POST /api/gfs/local-agent/token - Generate a new agent token
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { name, permissions, expiresInDays } = body;

    if (!name) {
      return NextResponse.json(
        { error: 'Token name is required' },
        { status: 400 }
      );
    }

    // Generate a secure random token
    const rawToken = crypto.randomBytes(32).toString('hex');
    const tokenHash = crypto.createHash('sha256').update(rawToken).digest('hex');

    // Calculate expiration
    let expiresAt: Date | null = null;
    if (expiresInDays) {
      expiresAt = new Date();
      expiresAt.setDate(expiresAt.getDate() + expiresInDays);
    }

    // Create token record
    const tokenRecord = await prisma.localAgentToken.create({
      data: {
        name,
        tokenHash,
        permissions: permissions || ['status', 'ping', 'system_info'],
        expiresAt,
        isActive: true,
      },
    });

    return NextResponse.json({
      success: true,
      tokenId: tokenRecord.id,
      name: tokenRecord.name,
      // IMPORTANT: This is the only time the raw token is returned
      token: rawToken,
      expiresAt: tokenRecord.expiresAt,
      message: 'Save this token securely - it cannot be retrieved again!',
    });
  } catch (error) {
    console.error('Token generation error:', error);
    return NextResponse.json(
      { error: 'Failed to generate token' },
      { status: 500 }
    );
  }
}

// GET /api/gfs/local-agent/token - List tokens (without revealing values)
export async function GET() {
  try {
    const tokens = await prisma.localAgentToken.findMany({
      select: {
        id: true,
        name: true,
        machineId: true,
        isActive: true,
        permissions: true,
        lastUsed: true,
        expiresAt: true,
        createdAt: true,
      },
      orderBy: { createdAt: 'desc' },
    });

    return NextResponse.json({
      success: true,
      tokens,
    });
  } catch (error) {
    console.error('List tokens error:', error);
    return NextResponse.json(
      { error: 'Failed to list tokens' },
      { status: 500 }
    );
  }
}

// DELETE /api/gfs/local-agent/token - Revoke a token
export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const tokenId = searchParams.get('id');

    if (!tokenId) {
      return NextResponse.json(
        { error: 'Token ID is required' },
        { status: 400 }
      );
    }

    await prisma.localAgentToken.update({
      where: { id: tokenId },
      data: { isActive: false },
    });

    return NextResponse.json({
      success: true,
      message: 'Token revoked',
    });
  } catch (error) {
    console.error('Revoke token error:', error);
    return NextResponse.json(
      { error: 'Failed to revoke token' },
      { status: 500 }
    );
  }
}
