"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkspaceAuthConfigError = void 0;
exports.findWorkspaceAuthConfig = findWorkspaceAuthConfig;
const node_fs_1 = require("node:fs");
const node_path_1 = require("node:path");
class WorkspaceAuthConfigError extends Error {
    constructor(filePath, reason) {
        super(reason);
        this.name = 'WorkspaceAuthConfigError';
        this.filePath = filePath;
    }
}
exports.WorkspaceAuthConfigError = WorkspaceAuthConfigError;
const WORKSPACE_AUTH_FILENAME = '.playdrop.json';
function normalizeOwnerUsername(value) {
    if (typeof value !== 'string') {
        return null;
    }
    const normalized = value.trim();
    return normalized.length > 0 ? normalized : null;
}
function normalizeEnv(value) {
    if (typeof value !== 'string') {
        return undefined;
    }
    const normalized = value.trim();
    return normalized.length > 0 ? normalized : undefined;
}
function readWorkspaceAuthConfig(filePath) {
    let parsed;
    try {
        const raw = (0, node_fs_1.readFileSync)(filePath, 'utf8');
        parsed = JSON.parse(raw);
    }
    catch {
        throw new WorkspaceAuthConfigError(filePath, 'invalid_json');
    }
    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
        throw new WorkspaceAuthConfigError(filePath, 'invalid_shape');
    }
    const ownerUsername = normalizeOwnerUsername(parsed.ownerUsername);
    if (!ownerUsername) {
        throw new WorkspaceAuthConfigError(filePath, 'missing_owner_username');
    }
    return {
        ownerUsername,
        env: normalizeEnv(parsed.env),
    };
}
function findWorkspaceAuthConfig(startPath) {
    let current = (0, node_path_1.resolve)(startPath);
    if ((0, node_fs_1.existsSync)(current) && (0, node_fs_1.statSync)(current).isFile()) {
        current = (0, node_path_1.dirname)(current);
    }
    while (true) {
        const candidate = (0, node_path_1.join)(current, WORKSPACE_AUTH_FILENAME);
        if ((0, node_fs_1.existsSync)(candidate) && (0, node_fs_1.statSync)(candidate).isFile()) {
            const config = readWorkspaceAuthConfig(candidate);
            if (config) {
                return {
                    path: candidate,
                    directory: current,
                    config,
                };
            }
            return null;
        }
        const parent = (0, node_path_1.dirname)(current);
        if (parent === current) {
            return null;
        }
        current = parent;
    }
}
