import { agentIntegrations } from "@rudderhq/db";
import { and, eq } from "drizzle-orm";
import { badRequest } from "../../../errors.js";
import { secretService } from "../../secrets.js";
function firstString(value) {
    return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
function bodyAppId(body) {
    const header = body.header && typeof body.header === "object" ? body.header : null;
    return firstString(body.appId) ?? firstString(header?.app_id);
}
function parseCredentialValue(value) {
    try {
        const parsed = JSON.parse(value);
        if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
            const record = parsed;
            return {
                verificationToken: firstString(record.verificationToken) ?? firstString(record.verification_token),
                encryptKey: firstString(record.encryptKey) ?? firstString(record.encrypt_key),
            };
        }
    }
    catch {
        // Plain string credentials are treated as the callback verification token.
    }
    return { verificationToken: firstString(value), encryptKey: null };
}
export function feishuCallbackCredentialService(db) {
    const secrets = secretService(db);
    return {
        resolveForCallback: async (orgId, body) => {
            const appId = bodyAppId(body);
            if (!appId)
                return null;
            const integration = await db
                .select({
                appCredentialSecretId: agentIntegrations.appCredentialSecretId,
            })
                .from(agentIntegrations)
                .where(and(eq(agentIntegrations.orgId, orgId), eq(agentIntegrations.provider, "feishu"), eq(agentIntegrations.externalAppId, appId), eq(agentIntegrations.status, "active")))
                .then((rows) => {
                if (rows.length > 1) {
                    throw badRequest("Ambiguous Feishu integration for callback app_id");
                }
                return rows[0] ?? null;
            });
            if (!integration)
                return null;
            const value = await secrets.resolveSecretValue(orgId, integration.appCredentialSecretId, "latest");
            return parseCredentialValue(value);
        },
    };
}
//# sourceMappingURL=callback-credentials.js.map