"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const assert_1 = __importDefault(require("assert"));
const createDebugger_1 = __importDefault(require("../createDebugger"));
const sync_fetch_1 = require("./sync-fetch");
const debugLogger = (0, createDebugger_1.default)('config:initializeSession');
const uuidRegex = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;
const validateUUID = (uuid) => {
    return typeof uuid === 'string' && uuidRegex.test(uuid);
};
function initializeSession({ apiKey, projectId, serverURL, watcherVersion, sessionID, buildID, gitCommitSha, gitUrl, gitBranch, gitCommitAuthor, gitIsDirty, gitDefaultBranch, gitCommitMessage, gitTag, gitCommitEmail, configOverrides, runOptions, isCanonicalSource, bundledAxeCoreVersions }) {
    (0, assert_1.default)(apiKey, 'API key is required');
    (0, assert_1.default)(serverURL, 'Server URL is required');
    (0, assert_1.default)(watcherVersion, 'Watcher version is required');
    (0, assert_1.default)(!(sessionID && typeof sessionID !== 'string'), 'Session ID must be a string');
    (0, assert_1.default)(!(buildID && typeof buildID !== 'string'), 'Build ID must be a string');
    (0, assert_1.default)(!(sessionID && buildID), 'Session ID and Build ID are mutually exclusive. `sessionId` is deprecated, please use `buildID` instead');
    (0, assert_1.default)(!(gitCommitSha && typeof gitCommitSha !== 'string'), 'Git commit SHA must be a string');
    (0, assert_1.default)(gitUrl === null || typeof gitUrl === 'string', 'Git URL must be a string or null');
    (0, assert_1.default)(gitBranch === null || typeof gitBranch === 'string', 'Git Branch must be a string or null');
    (0, assert_1.default)(gitCommitAuthor === null || typeof gitCommitAuthor === 'string', 'Git Commit Author must be a string or null');
    (0, assert_1.default)(gitIsDirty === null || typeof gitIsDirty === 'boolean', 'Git Is Dirty must be a boolean or null');
    (0, assert_1.default)(gitDefaultBranch === null || typeof gitDefaultBranch === 'string', 'Git Default Branch must be a string or null');
    (0, assert_1.default)(gitCommitMessage === null || typeof gitCommitMessage === 'string', 'Git Commit Message must be a string or null');
    (0, assert_1.default)(gitTag === null || typeof gitTag === 'string', 'Git Tag must be a string or null');
    (0, assert_1.default)(gitCommitEmail === null || typeof gitCommitEmail === 'string', 'Git Commit Email must be a string or null');
    (0, assert_1.default)(configOverrides === null || typeof configOverrides === 'object', 'Configuration Overrides must be an object or null');
    (0, assert_1.default)(runOptions === null || typeof runOptions === 'object', 'Run Options must be an object or null');
    (0, assert_1.default)(projectId === null || validateUUID(projectId), 'Project ID must be a valid v4 UUID or null');
    const url = new URL(`/api-pub/watcher/sessions`, serverURL);
    if (isCanonicalSource) {
        debugLogger('Initializing session from canonical source');
    }
    const payload = {
        watcher_version: watcherVersion,
        session_id: sessionID,
        build_id: buildID,
        git_commit_sha: gitCommitSha,
        git_url: gitUrl,
        git_branch: gitBranch,
        git_commit_author: gitCommitAuthor,
        git_is_dirty: gitIsDirty,
        git_default_branch: gitDefaultBranch,
        git_commit_message: gitCommitMessage,
        git_tag: gitTag,
        git_commit_email: gitCommitEmail,
        watcher_config: {
            configuration_overrides: configOverrides
                ? {
                    accessibility_standard: configOverrides?.accessibilityStandard,
                    axe_core_version: configOverrides?.axeCoreVersion,
                    best_practices: configOverrides?.bestPractices,
                    experimental_rules: configOverrides?.experimentalRules
                }
                : null,
            run_options: runOptions
        },
        ...(projectId && { project_id: projectId }),
        is_canonical_source: isCanonicalSource,
        bundled_axe_core_versions: bundledAxeCoreVersions || []
    };
    const res = (0, sync_fetch_1.syncFetch)(url.toString(), {
        headers: {
            'X-API-Key': apiKey,
            'Content-Type': 'application/json'
        },
        method: 'POST',
        body: JSON.stringify(payload)
    });
    const body = res.body;
    const error = body.error || (body.errors?.length && body.errors[0]);
    if (error) {
        debugLogger('Error initializing session:', error);
        throw new Error(error);
    }
    if (body.warnings.length) {
        debugLogger('Warning initializing session:', body.warnings);
        console.warn(body.warnings.join(', '));
    }
    debugLogger('Session initialized successfully:', body.session_id);
    if (body.axe_core_settings) {
        debugLogger('Axe Core settings:', body.axe_core_settings);
    }
    return {
        session_id: body.session_id,
        axe_core_settings: body.axe_core_settings
    };
}
exports.default = initializeSession;
//# sourceMappingURL=initializeSession.js.map