/**
 * studiograph admin transfer-ownership — flip the workspace owner role.
 *
 * One-way change. Wraps POST /api/auth/transfer-ownership, which gates on
 * `user.role === 'owner'` server-side. The current owner runs this on
 * their laptop using their stored sg_ token; after the call returns OK
 * the *new* owner can transfer it back via the web UI or by re-running
 * this command with their own token. The CLI command itself does not
 * re-verify roles — that's the server's job.
 *
 * Targeting is by email (operator-friendly) rather than userId; we
 * resolve email → userId via GET /api/auth/users before the POST.
 */
import { Command } from 'commander';
import { intro, outro, log, confirm, isCancel } from '@clack/prompts';
import { Workspace } from '../../../core/workspace.js';
import { getStudiographToken } from '../../../core/user-config.js';
export const adminTransferOwnershipCommand = new Command('transfer-ownership')
    .description('Transfer workspace ownership to another user (owner only)')
    .argument('<email>', 'Email of the user who should become the new owner')
    .option('--token <value>', 'Server API token (also reads STUDIOGRAPH_TOKEN)')
    .option('--server-url <url>', 'Server URL (default: workspace.server_url from workspace.json)')
    .option('--yes', 'Skip confirmation prompt')
    .action(async (targetEmail, opts) => {
    intro('Transfer workspace ownership');
    const workspace = new Workspace();
    if (!workspace.isWorkspace()) {
        outro('Not a Studiograph workspace. Run from your workspace root.');
        process.exit(1);
        return;
    }
    const config = await workspace.loadConfig();
    const serverUrl = (opts.serverUrl ?? config.server_url)?.replace(/\/+$/, '');
    if (!serverUrl) {
        outro('No server URL configured. Pass --server-url <url>, or run this from a workspace cloned via `studiograph clone`.');
        process.exit(1);
        return;
    }
    // Precedence: --token flag → STUDIOGRAPH_TOKEN env → stored token in user.json.
    const token = opts.token?.trim() || process.env.STUDIOGRAPH_TOKEN?.trim() || getStudiographToken(serverUrl);
    if (!token) {
        outro(`No API token for ${serverUrl}. Run \`studiograph admin token issue ${serverUrl}\` first, or pass --token / STUDIOGRAPH_TOKEN.`);
        process.exit(1);
        return;
    }
    // Step 1: resolve email → userId. /api/auth/users requires authentication
    // (any user can list, gated by requireUser). With Bearer sg_ accepted at
    // src/server/routes/auth-api.ts:requireUser the CLI auth flows through.
    const usersRes = await fetch(`${serverUrl}/api/auth/users`, {
        headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
    });
    if (!usersRes.ok) {
        outro(`Could not list users (${usersRes.status} ${usersRes.statusText}).`);
        process.exit(1);
        return;
    }
    const { users } = (await usersRes.json());
    const needle = targetEmail.trim().toLowerCase();
    const target = users.find((u) => u.email.toLowerCase() === needle);
    if (!target) {
        outro(`No user with email ${targetEmail}. Known users: ${users.map((u) => u.email).join(', ') || '(none)'}.`);
        process.exit(1);
        return;
    }
    if (target.role === 'owner') {
        outro(`${target.email} is already the workspace owner — nothing to do.`);
        return;
    }
    // Step 2: confirm. Transferring ownership is one-way (the caller
    // demotes themselves to admin), so the operator gets one explicit
    // chance to bail unless they passed --yes.
    if (!opts.yes && process.stdout.isTTY) {
        const display = target.displayName ?? target.display_name ?? target.email;
        const ok = await confirm({
            message: `Transfer ownership to ${display} (${target.email})? You will be demoted to member.`,
            initialValue: false,
        });
        if (!ok || isCancel(ok)) {
            outro('Cancelled');
            process.exit(0);
            return;
        }
    }
    // Step 3: POST. Server enforces caller-is-owner; we just send the request.
    const res = await fetch(`${serverUrl}/api/auth/transfer-ownership`, {
        method: 'POST',
        headers: {
            Authorization: `Bearer ${token}`,
            'Content-Type': 'application/json',
            Accept: 'application/json',
        },
        body: JSON.stringify({ targetUserId: target.id }),
    });
    if (!res.ok) {
        const text = await res.text();
        outro(`Transfer failed (${res.status}): ${text}`);
        process.exit(1);
        return;
    }
    log.success(`Ownership transferred to ${target.email}.`);
    log.message('Your role is now `member`. The new owner can transfer it back via\n' +
        '  studiograph admin transfer-ownership <your-email>\n' +
        'or from the web UI (Settings → Team).');
    outro('Done.');
});
//# sourceMappingURL=transfer-ownership.js.map