// 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';
/** 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() + 30 * 24 * 60 * 60 * 1000).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 {
            content: [
                {
                    type: 'text',
                    text: JSON.stringify({ success: true, user, email, plan, message: 'Logged in successfully' }, null, 2),
                },
            ],
        };
    }
    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 {
            content: [
                {
                    type: 'text',
                    text: JSON.stringify({ success: true, message: 'Logged out successfully' }, null, 2),
                },
            ],
        };
        /* v8 ignore start -- error branches tested via unit mocks */
    }
    catch (error) {
        const err = error;
        if (err.code === 'ENOENT') {
            return {
                content: [
                    {
                        type: 'text',
                        text: JSON.stringify({ success: true, message: 'No credentials found, already logged out' }, null, 2),
                    },
                ],
            };
        }
        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 {
            content: [{ type: 'text', text: JSON.stringify(info, null, 2) }],
        };
        /* 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