"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatGovernanceUploadLimitError = formatGovernanceUploadLimitError;
const governanceUploadClient_1 = require("./governanceUploadClient");
const pricingUrl = 'https://archpilot.org/pricing';
function isRecord(value) {
    return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
function collectResponseRecords(response) {
    if (!isRecord(response)) {
        return [];
    }
    const records = [response];
    const nestedCandidates = [response.error, response.details];
    for (const candidate of nestedCandidates) {
        if (isRecord(candidate)) {
            records.push(candidate);
            if (isRecord(candidate.details)) {
                records.push(candidate.details);
            }
        }
    }
    return records;
}
function readString(records, key) {
    for (const record of records) {
        const value = record[key];
        if (typeof value === 'string' && value.trim().length > 0) {
            return value.trim();
        }
    }
    return undefined;
}
function readDisplayValue(records, key) {
    for (const record of records) {
        const value = record[key];
        if (typeof value === 'number' && Number.isFinite(value)) {
            return String(value);
        }
        if (typeof value === 'string' && value.trim().length > 0) {
            return value.trim();
        }
    }
    return 'unknown';
}
function resolveUploadLimitErrorCode(records) {
    const code = readString(records, 'code');
    if (code === 'UPLOAD_MONTHLY_QUOTA_EXCEEDED' ||
        code === 'UPLOAD_RATE_LIMIT_EXCEEDED' ||
        code === 'UPLOAD_PAYLOAD_LIMIT_EXCEEDED') {
        return code;
    }
    return undefined;
}
function formatUtcDate(value) {
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) {
        return value;
    }
    const months = [
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
        'August',
        'September',
        'October',
        'November',
        'December',
    ];
    return `${months[date.getUTCMonth()]} ${date.getUTCDate()}, ${date.getUTCFullYear()}`;
}
function formatMonthlyQuotaExceeded(records) {
    const used = readDisplayValue(records, 'used');
    const limit = readDisplayValue(records, 'limit');
    const resetAt = readString(records, 'resetAt');
    return {
        code: 'UPLOAD_MONTHLY_QUOTA_EXCEEDED',
        notificationMessage: 'ArchPilot governance upload failed: monthly upload limit reached.',
        message: [
            'ArchPilot Governance Upload Failed',
            '',
            'Reason:',
            `You have reached your monthly governance upload limit (${used} / ${limit}).`,
            '',
            'Next reset:',
            resetAt ? formatUtcDate(resetAt) : 'unknown',
            '',
            'What you can do:',
            '- Wait for the quota to reset, or',
            '- Upgrade your plan for higher limits',
            '',
            'Upgrade:',
            pricingUrl,
        ].join('\n'),
    };
}
function formatPayloadLimitExceeded(records) {
    const received = readDisplayValue(records, 'received');
    const type = readDisplayValue(records, 'type');
    const limit = readDisplayValue(records, 'limit');
    return {
        code: 'UPLOAD_PAYLOAD_LIMIT_EXCEEDED',
        notificationMessage: 'ArchPilot governance upload failed: payload exceeds plan limit.',
        message: [
            'ArchPilot Governance Upload Failed',
            '',
            'Reason:',
            `This upload contains ${received} ${type}, which exceeds your plan limit (${limit}).`,
            '',
            'What you can do:',
            '- Reduce the scope of this upload, or',
            '- Upgrade your plan to increase limits',
            '',
            'Upgrade:',
            pricingUrl,
        ].join('\n'),
    };
}
function formatRateLimitExceeded() {
    return {
        code: 'UPLOAD_RATE_LIMIT_EXCEEDED',
        notificationMessage: 'ArchPilot governance upload throttled. Please retry shortly.',
        message: [
            'ArchPilot Governance Upload Throttled',
            '',
            'Reason:',
            'Upload rate limit exceeded. Please retry shortly.',
            '',
            'Note:',
            'This is a temporary protection limit and will reset automatically.',
        ].join('\n'),
    };
}
function formatGovernanceUploadLimitError(error) {
    if (!(error instanceof governanceUploadClient_1.GovernanceUploadHttpError)) {
        return undefined;
    }
    const records = collectResponseRecords(error.response);
    const code = resolveUploadLimitErrorCode(records);
    if (code === 'UPLOAD_MONTHLY_QUOTA_EXCEEDED') {
        return formatMonthlyQuotaExceeded(records);
    }
    if (code === 'UPLOAD_PAYLOAD_LIMIT_EXCEEDED') {
        return formatPayloadLimitExceeded(records);
    }
    if (code === 'UPLOAD_RATE_LIMIT_EXCEEDED') {
        return formatRateLimitExceeded();
    }
    return undefined;
}
//# sourceMappingURL=governanceUploadLimitErrorFormatting.js.map