// @crash-shield-ignore-file — config/cache reader for Planu-controlled JSON; writer is this codebase, shape guaranteed by build/seed.
// tools/registry/auth.ts — AC-8: Authentication handlers for registry
import { readFile, writeFile, mkdir, unlink, chmod } from 'node:fs/promises';
import { join } from 'node:path';
import { homedir } from 'node:os';
import { compactResult } from '../output-formatter.js';
/** 30-day expiry in milliseconds */
const TOKEN_EXPIRY_MS = 30 * 24 * 60 * 60 * 1000;
/** Path to the credentials file. */
function credentialsPath() {
    return join(homedir(), '.planu', 'credentials.json');
}
/**
 * Handle registry_login tool invocation.
 * Stores the given token and user info to ~/.planu/credentials.json with 0o600 permissions.
 */
export async function handleRegistryLogin(args) {
    try {
        const token = args.token;
        const user = args.user;
        const email = args.email;
        const rawPlan = args.plan;
        const plan = rawPlan ?? 'free';
        const expiresAt = args.expiresAt;
        if (!token || !user || !email) {
            return {
                content: [
                    { type: 'text', text: 'Missing required fields: token, user, and email' },
                ],
                isError: true,
            };
        }
        const credentials = {
            token,
            user,
            email,
            plan,
            expiresAt: expiresAt ?? new Date(Date.now() + TOKEN_EXPIRY_MS).toISOString(),
        };
        const credPath = credentialsPath();
        await mkdir(join(homedir(), '.planu'), { recursive: true });
        await writeFile(credPath, JSON.stringify(credentials, null, 2), 'utf-8');
        await chmod(credPath, 0o600);
        return compactResult([
            `Done: Logged in successfully`,
            `**user**: ${user}`,
            `**email**: ${email}`,
            `**plan**: ${plan}`,
        ].join('\n'));
    }
    catch (error) {
        /* v8 ignore start -- unexpected runtime errors */
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: `Registry login failed: ${message}` }],
            isError: true,
        };
        /* v8 ignore stop */
    }
}
/**
 * Handle registry_logout tool invocation.
 * Removes the credentials file.
 */
export async function handleRegistryLogout(_args) {
    try {
        await unlink(credentialsPath());
        return compactResult('Done: Logged out successfully');
        /* v8 ignore start -- error branches tested via unit mocks */
    }
    catch (error) {
        const err = error;
        if (err.code === 'ENOENT') {
            return compactResult('Done: No credentials found, already logged out');
        }
        return {
            content: [{ type: 'text', text: `Registry logout failed: ${err.message}` }],
            isError: true,
        };
    }
    /* v8 ignore stop */
}
/**
 * Handle registry_whoami tool invocation.
 * Reads and returns stored credentials (without the raw token).
 */
export async function handleRegistryWhoami(_args) {
    try {
        const raw = await readFile(credentialsPath(), 'utf-8');
        const cred = JSON.parse(raw);
        const isExpired = new Date(cred.expiresAt) <= new Date();
        const info = {
            user: cred.user,
            email: cred.email,
            plan: cred.plan,
            expiresAt: cred.expiresAt,
            expired: isExpired,
            authenticated: !isExpired,
        };
        return compactResult([
            `**user**: ${info.user}`,
            `**email**: ${info.email}`,
            `**plan**: ${info.plan}`,
            `**expiresAt**: ${info.expiresAt}`,
            `**expired**: ${String(info.expired)}`,
            `**authenticated**: ${String(info.authenticated)}`,
        ].join('\n'));
        /* v8 ignore start -- error branches tested via unit mocks */
    }
    catch (error) {
        const err = error;
        if (err.code === 'ENOENT') {
            return {
                content: [{ type: 'text', text: 'Not authenticated. Run registry_login first.' }],
                isError: true,
            };
        }
        return {
            content: [{ type: 'text', text: `Registry whoami failed: ${err.message}` }],
            isError: true,
        };
    }
    /* v8 ignore stop */
}
//# sourceMappingURL=auth.js.map