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

interface ServerData {
  id: number;
  name: string;
  ip: string;
  ssh_key_path?: string | null;
  key_generated?: boolean;
}

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) as ServerData | null;
    
    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.key_generated) {
      return NextResponse.json(
        { error: 'Public key not available for user-provided keys' },
        { status: 403 }
      );
    }

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

    const sshService = getSSHService();
    const publicKey = sshService.getPublicKey(server.ssh_key_path);
    
    return NextResponse.json({
      success: true,
      publicKey,
      serverName: server.name,
      serverIp: server.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 }
    );
  }
}
