import { Router } from "express";
import { eq, and } from "drizzle-orm";
import { toolConnections } from "@zmeel/db";
import { assertBoard, assertCompanyAccess } from "./authz.js";
export function toolConnectionRoutes(db) {
    const router = Router();
    // GET /companies/:companyId/tools — list connected tools
    router.get("/companies/:companyId/tools", async (req, res) => {
        const companyId = req.params.companyId;
        assertCompanyAccess(req, companyId);
        assertBoard(req);
        try {
            const connections = await db
                .select()
                .from(toolConnections)
                .where(eq(toolConnections.companyId, companyId));
            res.json(connections);
        }
        catch (err) {
            console.error("[tool-connections] list failed:", err);
            res.status(500).json({ error: "Failed to list tool connections" });
        }
    });
    // POST /companies/:companyId/tools/:appName/connect — initiate OAuth
    router.post("/companies/:companyId/tools/:appName/connect", async (req, res) => {
        const companyId = req.params.companyId;
        const appName = req.params.appName;
        assertCompanyAccess(req, companyId);
        assertBoard(req);
        try {
            const composioService = await import("../services/composio.js");
            const userId = req.actor.userId ?? "board";
            const redirectUrl = req.body?.redirectUrl ||
                `${req.protocol}://${req.get("host")}/api/tools/oauth/callback`;
            const result = await composioService.initiateConnection(userId, appName, redirectUrl);
            if (!result) {
                res.status(503).json({ error: "Composio service not available" });
                return;
            }
            await db.insert(toolConnections).values({
                companyId,
                userId,
                appName,
                composioEntityId: userId,
                composioConnectionId: result.connectedAccountId,
                status: "pending",
            });
            res.json({
                redirectUrl: result.redirectUrl,
                connectedAccountId: result.connectedAccountId,
            });
        }
        catch (err) {
            console.error("[tool-connections] connect failed:", err);
            res.status(500).json({ error: "Failed to initiate connection" });
        }
    });
    // DELETE /companies/:companyId/tools/:appName — disconnect a tool
    router.delete("/companies/:companyId/tools/:appName", async (req, res) => {
        const companyId = req.params.companyId;
        const appName = req.params.appName;
        assertCompanyAccess(req, companyId);
        assertBoard(req);
        try {
            const deleted = await db
                .delete(toolConnections)
                .where(and(eq(toolConnections.companyId, companyId), eq(toolConnections.appName, appName)))
                .returning();
            if (deleted.length === 0) {
                res.status(404).json({ error: "Tool connection not found" });
                return;
            }
            res.json({ ok: true });
        }
        catch (err) {
            console.error("[tool-connections] disconnect failed:", err);
            res.status(500).json({ error: "Failed to disconnect tool" });
        }
    });
    // GET /tools/available — list all available apps from Composio
    router.get("/tools/available", async (req, res) => {
        assertBoard(req);
        try {
            const composioService = await import("../services/composio.js");
            const apps = await composioService.listAvailableApps();
            res.json(apps);
        }
        catch (err) {
            console.error("[tool-connections] listAvailableApps failed:", err);
            res.status(500).json({ error: "Failed to list available apps" });
        }
    });
    // GET /tools/oauth/callback — OAuth callback redirect
    router.get("/tools/oauth/callback", async (req, res) => {
        try {
            const connectionId = req.query.connectedAccountId;
            if (connectionId) {
                await db
                    .update(toolConnections)
                    .set({
                    status: "active",
                    connectedAt: new Date(),
                    updatedAt: new Date(),
                })
                    .where(eq(toolConnections.composioConnectionId, connectionId));
            }
            // Redirect back to the UI
            res.redirect("/settings/tools?connected=true");
        }
        catch (err) {
            console.error("[tool-connections] oauth callback failed:", err);
            res.redirect("/settings/tools?error=callback_failed");
        }
    });
    return router;
}
//# sourceMappingURL=tool-connections.js.map