import { getPrismaClient } from '../db/prisma.js';
import { encryptString } from '../crypto/envelope.js';
import { requireAuth } from '../middleware/auth.js';
import { readRateLimit, writeRateLimit } from '../middleware/rateLimit.js';
export async function toolCredentialRoutes(fastify) {
    fastify.post('/api/tool-credentials', {
        preHandler: [requireAuth, writeRateLimit],
    }, async (request, reply) => {
        try {
            const { tool, version, credential, metadata } = (request.body || {});
            if (!tool || !version || !credential) {
                return reply.status(400).send({
                    error: 'Missing required fields',
                    required: ['tool', 'version', 'credential'],
                });
            }
            const kekBase64 = process.env['KEK_BASE64'];
            if (!kekBase64) {
                return reply.status(500).send({
                    error: 'Encryption not configured',
                    message: 'KEK_BASE64 environment variable not set',
                });
            }
            const kek = Buffer.from(kekBase64, 'base64');
            const encryptedCredential = encryptString(credential, kek);
            const encryptedMetadata = metadata ? encryptString(JSON.stringify(metadata), kek) : null;
            const prisma = await getPrismaClient();
            const toolCredential = await prisma.toolCredential.create({
                data: {
                    tool,
                    version,
                    isActive: false,
                    encryptedCredential,
                    metadata: encryptedMetadata,
                },
            });
            return reply.status(201).send({
                success: true,
                message: 'Tool credential stored successfully (encrypted)',
                id: toolCredential.id,
                tool: toolCredential.tool,
                version: toolCredential.version,
                isActive: toolCredential.isActive,
                persistent: true,
            });
        }
        catch (error) {
            const msg = error instanceof Error ? error.message : String(error);
            console.error('[ToolCredentials] Error storing credential:', msg);
            return reply.status(500).send({
                error: 'Failed to store credential',
                details: msg,
            });
        }
    });
    fastify.post('/api/tool-credentials/:id/activate', {
        preHandler: [requireAuth, writeRateLimit],
    }, async (request, reply) => {
        try {
            const { id } = request.params;
            const prisma = await getPrismaClient();
            const credential = await prisma.toolCredential.findUnique({
                where: { id },
            });
            if (!credential) {
                return reply.status(404).send({
                    error: 'Credential not found',
                });
            }
            await prisma.toolCredential.updateMany({
                where: {
                    tool: credential.tool,
                    isActive: true,
                },
                data: {
                    isActive: false,
                    deactivatedAt: new Date(),
                },
            });
            const activated = await prisma.toolCredential.update({
                where: { id },
                data: {
                    isActive: true,
                    activatedAt: new Date(),
                },
            });
            return reply.status(200).send({
                success: true,
                message: 'Credential activated successfully',
                id: activated.id,
                tool: activated.tool,
                version: activated.version,
                isActive: activated.isActive,
                activatedAt: activated.activatedAt,
            });
        }
        catch (error) {
            const msg = error instanceof Error ? error.message : String(error);
            console.error('[ToolCredentials] Error activating credential:', msg);
            return reply.status(500).send({
                error: 'Failed to activate credential',
                details: msg,
            });
        }
    });
    fastify.get('/api/tool-credentials/:tool', {
        preHandler: [requireAuth, readRateLimit],
    }, async (request, reply) => {
        try {
            const { tool } = request.params;
            const prisma = await getPrismaClient();
            const credential = await prisma.toolCredential.findFirst({
                where: {
                    tool,
                    isActive: true,
                },
            });
            if (!credential) {
                return reply.status(404).send({
                    error: 'No active credential found for tool',
                    tool,
                });
            }
            return reply.status(200).send({
                id: credential.id,
                tool: credential.tool,
                version: credential.version,
                isActive: credential.isActive,
                createdAt: credential.createdAt,
                activatedAt: credential.activatedAt,
                persistent: true,
            });
        }
        catch (error) {
            const msg = error instanceof Error ? error.message : String(error);
            console.error('[ToolCredentials] Error getting credential:', msg);
            return reply.status(500).send({
                error: 'Failed to get credential',
                details: msg,
            });
        }
    });
    fastify.get('/api/tool-credentials', {
        preHandler: [requireAuth, readRateLimit],
    }, async (_request, reply) => {
        try {
            const prisma = await getPrismaClient();
            const credentials = await prisma.toolCredential.findMany({
                orderBy: {
                    createdAt: 'desc',
                },
            });
            const response = credentials.map((cred) => ({
                id: cred.id,
                tool: cred.tool,
                version: cred.version,
                isActive: cred.isActive,
                createdAt: cred.createdAt,
                activatedAt: cred.activatedAt,
                deactivatedAt: cred.deactivatedAt,
                persistent: true,
            }));
            return reply.status(200).send({
                success: true,
                credentials: response,
                total: response.length,
                storage: 'PostgreSQL (encrypted)',
            });
        }
        catch (error) {
            const msg = error instanceof Error ? error.message : String(error);
            console.error('[ToolCredentials] Error listing credentials:', msg);
            return reply.status(500).send({
                error: 'Failed to list credentials',
                details: msg,
            });
        }
    });
    fastify.delete('/api/tool-credentials/:id', {
        preHandler: [requireAuth, writeRateLimit],
    }, async (request, reply) => {
        try {
            const { id } = request.params;
            const prisma = await getPrismaClient();
            await prisma.toolCredential.delete({
                where: { id },
            });
            return reply.status(200).send({
                success: true,
                message: 'Credential deleted successfully',
                id,
            });
        }
        catch (error) {
            const msg = error instanceof Error ? error.message : String(error);
            console.error('[ToolCredentials] Error deleting credential:', msg);
            if (typeof error === 'object' && error !== null && error.code === 'P2025') {
                return reply.status(404).send({
                    error: 'Credential not found',
                });
            }
            return reply.status(500).send({
                error: 'Failed to delete credential',
                details: msg,
            });
        }
    });
}
//# sourceMappingURL=tool-credentials.js.map