import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { getDatabase } from '../../../../../server/database-prisma';
import { getSSHService } from '../../../../../server/ssh-service';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id: idParam } = await params;
    const id = parseInt(idParam);
    if (isNaN(id)) {
      return NextResponse.json(
        { error: 'Invalid server ID' },
        { status: 400 }
      );
    }

    const db = getDatabase();
    const server = await db.getServerById(id);
    
    if (!server) {
      return NextResponse.json(
        { error: 'Server not found' },
        { status: 404 }
      );
    }

    // Only allow viewing public key if it was generated by the system
    if (!(server as any).key_generated) {
      return NextResponse.json(
        { error: 'Public key not available for user-provided keys' },
        { status: 403 }
      );
    }

    if (!(server as any).ssh_key_path) {
      return NextResponse.json(
        { error: 'SSH key path not found' },
        { status: 404 }
      );
    }

    const sshService = getSSHService();
    const publicKey = sshService.getPublicKey((server as any).ssh_key_path as string);
    
    return NextResponse.json({
      success: true,
      publicKey,
      serverName: (server as any).name,
      serverIp: (server as any).ip
    });
  } catch (error) {
    console.error('Error retrieving public key:', error);
    return NextResponse.json(
      { 
        success: false,
        error: error instanceof Error ? error.message : String(error)
      },
      { status: 500 }
    );
  }
}
