import { getFigmaConfig, saveFigmaConfig, getFigmaSyncLog, getFigmaFiles, saveFigmaFiles, } from '../../storage/figma-store.js';
import { getFigmaMe } from '../../engine/figma/api-client.js';
import { parseAndValidateFileEntry, addFileEntry, removeFileEntry, } from '../../engine/figma/multi-file-manager.js';
import { FIGMA_NOT_CONNECTED } from './shared.js';
function maskToken(token) {
    if (token.length <= 4) {
        return '****';
    }
    const last4 = token.slice(-4);
    return `****${last4}`;
}
export async function handleConfigureFigma(input) {
    let meResult;
    try {
        meResult = await getFigmaMe(input.accessToken);
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        return {
            content: [{ type: 'text', text: `Invalid Figma token: ${msg}` }],
            isError: true,
        };
    }
    const now = new Date().toISOString();
    const existing = await getFigmaConfig(input.projectPath);
    const config = {
        accessToken: input.accessToken,
        projectPath: input.projectPath,
        tokenType: 'pat',
        userName: meResult.name,
        connectedAt: existing?.connectedAt ?? now,
        updatedAt: now,
    };
    await saveFigmaConfig(input.projectPath, config);
    const maskedToken = maskToken(input.accessToken);
    const lines = [
        'Figma configured successfully.',
        '',
        '| Field | Value |',
        '|-------|-------|',
        `| Usuario | ${meResult.name} |`,
        `| Token | ${maskedToken} |`,
        `| Conectado en | ${now} |`,
    ];
    return { content: [{ type: 'text', text: lines.join('\n') }] };
}
export async function handleFigmaStatus(input) {
    const config = await getFigmaConfig(input.projectPath);
    if (config === null) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'Figma no está conectado. Usa start_oauth_flow con integration="figma" para autorizar en ~10 segundos.',
                },
            ],
        };
    }
    const syncLog = await getFigmaSyncLog(input.projectPath);
    const lastEntries = syncLog.slice(-3);
    const lines = [
        '**Figma Configuration**',
        '',
        '| Field | Value |',
        '|-------|-------|',
        `| Usuario | ${config.userName ?? '(unknown)'} |`,
        `| Token type | ${config.tokenType} |`,
        `| Connected at | ${config.connectedAt} |`,
        `| Updated at | ${config.updatedAt} |`,
    ];
    if (lastEntries.length > 0) {
        lines.push('', '**Last Sync Entries**', '');
        for (const entry of lastEntries) {
            const errPart = entry.error !== undefined ? ` — ${entry.error}` : '';
            lines.push(`- ${entry.syncedAt.slice(0, 19)} | ${entry.status} | ${entry.specsCreated} specs, ${entry.framesProcessed} frames${errPart}`);
        }
    }
    return { content: [{ type: 'text', text: lines.join('\n') }] };
}
export async function handleAddFigmaFile(input) {
    const config = await getFigmaConfig(input.projectPath);
    if (config === null) {
        return FIGMA_NOT_CONNECTED;
    }
    let entry;
    try {
        entry = parseAndValidateFileEntry(input.figmaUrl, input.label);
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        return { content: [{ type: 'text', text: `Error: ${msg}` }], isError: true };
    }
    const existing = await getFigmaFiles(input.projectPath);
    let updated;
    try {
        updated = addFileEntry(existing, entry);
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        return { content: [{ type: 'text', text: `Error: ${msg}` }], isError: true };
    }
    await saveFigmaFiles(input.projectPath, updated);
    return {
        content: [{ type: 'text', text: `Figma file added: [${input.label}] ${entry.fileKey}` }],
    };
}
export async function handleRemoveFigmaFile(input) {
    const existing = await getFigmaFiles(input.projectPath);
    const updated = removeFileEntry(existing, input.fileKey);
    await saveFigmaFiles(input.projectPath, updated);
    const removed = existing.length - updated.length;
    if (removed === 0) {
        return { content: [{ type: 'text', text: `File ${input.fileKey} not found.` }], isError: true };
    }
    return { content: [{ type: 'text', text: `Figma file ${input.fileKey} removed.` }] };
}
export async function handleListFigmaFiles(input) {
    const files = await getFigmaFiles(input.projectPath);
    if (files.length === 0) {
        return { content: [{ type: 'text', text: 'No Figma files registered. Use add_figma_file.' }] };
    }
    const lines = ['| Label | File Key | Added |', '|-------|----------|-------|'];
    for (const f of files) {
        lines.push(`| ${f.label} | ${f.fileKey} | ${f.addedAt.slice(0, 10)} |`);
    }
    return { content: [{ type: 'text', text: lines.join('\n') }] };
}
//# sourceMappingURL=config.js.map