import { getSession } from "../lib/neo4j.js";
import { encrypt } from "../lib/crypto.js";
import { loopGet, LoopApiError } from "../lib/loop-api.js";
const ALL_PERMISSIONS = ["properties", "people", "viewings", "feedback", "team", "marketing", "customer", "supplier"];
export async function keyRegister(params) {
    const { teamName, apiKey, accountId } = params;
    const permissions = params.permissions ?? ALL_PERMISSIONS;
    // Validate key against Loop API — try /team endpoint
    let teamAddress = "";
    let agentId = "";
    let warning;
    try {
        const teamData = await loopGet(apiKey, "/team", "loop-key-register", teamName);
        if (Array.isArray(teamData) && teamData.length === 0) {
            // 204 was converted to empty array — ambiguous scope
            warning =
                "Key accepted but Loop returned no team data (204). " +
                    "Verify the key's scope in Loop's dashboard.";
        }
        else if (teamData && typeof teamData === "object") {
            teamAddress = String(teamData.address ?? "");
            agentId = String(teamData.agentId ?? teamData.id ?? "");
        }
    }
    catch (err) {
        if (err instanceof LoopApiError && err.status === 401) {
            throw new Error(`Loop API rejected the key for team "${teamName}" (HTTP 401). ` +
                `Check that the key is valid and not expired.`);
        }
        // Network/timeout errors — still reject, key is unverified
        throw new Error(`Could not validate key against Loop API: ${err instanceof Error ? err.message : String(err)}`);
    }
    // Encrypt and store
    const encryptedKey = encrypt(apiKey);
    const now = new Date().toISOString();
    const writeSession = getSession();
    try {
        await writeSession.run(`CREATE INDEX loop_team_key_account_team IF NOT EXISTS
       FOR (k:LoopTeamKey) ON (k.accountId, k.teamName)`, {});
        const mergeResult = await writeSession.run(`MERGE (k:LoopTeamKey {teamName: $teamName, accountId: $accountId})
       ON CREATE SET
         k.encryptedKey = $encryptedKey,
         k.teamAddress = $teamAddress,
         k.agentId = $agentId,
         k.permissions = $permissions,
         k.createdAt = $now,
         k.updatedAt = $now
       RETURN k.createdAt = $now AS created`, { teamName, encryptedKey, teamAddress, agentId, accountId, permissions, now });
        const created = mergeResult.records[0]?.get("created");
        if (!created) {
            throw new Error(`Team "${teamName}" is already registered for this account.`);
        }
    }
    finally {
        await writeSession.close();
    }
    console.error(`[loop] key-register team=${teamName} account=${accountId}`);
    return { warning };
}
//# sourceMappingURL=key-register.js.map