"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.authManager = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const os_1 = __importDefault(require("os"));
const jose = __importStar(require("jose"));
const REPOBURG_DIR = path_1.default.join(os_1.default.homedir(), '.repoburg');
const TOKEN_PATH = path_1.default.join(REPOBURG_DIR, 'token.jwt');
const PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAcNJkxXJrYEa4cZmcq80A1Ns0y/HIt/WWEiWJ5F3E9ZE=
-----END PUBLIC KEY-----`;
class AuthManager {
    constructor() {
        this.publicKey = null;
        this.loadPublicKey();
    }
    async loadPublicKey() {
        try {
            const keyData = PUBLIC_KEY;
            console.log(`[AuthManager] Loading hardcoded public key: ${keyData.substring(0, 50)}...`);
            this.publicKey = await jose.importSPKI(keyData, 'EdDSA');
        }
        catch (error) {
            console.error('FATAL: Could not load JWT public key.', error);
            process.exit(1);
        }
    }
    async getAuthStatus() {
        if (!this.publicKey) {
            console.error('[AuthManager] Public key not loaded, cannot verify auth status.');
            return 'invalid';
        }
        try {
            const token = await fs_extra_1.default.readFile(TOKEN_PATH, 'utf-8');
            console.log(`[AuthManager] Verifying token from ${TOKEN_PATH}. Token starts with: ${token.substring(0, 20)}...`);
            try {
                const decoded = jose.decodeJwt(token);
                console.log('[AuthManager] Decoded JWT payload for debugging:', decoded);
            }
            catch (decodeError) {
                console.warn('[AuthManager] Could not decode JWT, it might be malformed.', decodeError);
            }
            await jose.jwtVerify(token, this.publicKey, {
                issuer: 'repoburg.com',
                audience: 'repoburg-daemon',
            });
            console.log('[AuthManager] JWT verification successful.');
            return 'authorized';
        }
        catch (error) {
            if (error instanceof Error) {
                if ('code' in error && error.code === 'ENOENT') {
                    console.log(`[AuthManager] No token file found at ${TOKEN_PATH}.`);
                    return 'unauthorized'; // No token file
                }
                if ('code' in error && error.code === 'ERR_JWT_EXPIRED') {
                    console.warn('[AuthManager] JWT has expired.');
                    return 'expired';
                }
                console.warn('[AuthManager] JWT verification failed:', error.message, error);
            }
            else {
                console.warn('[AuthManager] An unknown error occurred during JWT verification:', error);
            }
            return 'invalid';
        }
    }
    async verifyToken(token) {
        if (!this.publicKey) {
            console.error('[AuthManager] Public key not loaded, cannot verify token.');
            return false;
        }
        try {
            await jose.jwtVerify(token, this.publicKey, {
                issuer: 'repoburg.com',
                audience: 'repoburg-daemon',
            });
            console.log('[AuthManager] Passed-in JWT verification successful.');
            return true;
        }
        catch (error) {
            console.warn('[AuthManager] Passed-in JWT verification failed:', error.message);
            return false;
        }
    }
    async saveToken(token) {
        try {
            await fs_extra_1.default.ensureDir(REPOBURG_DIR);
            await fs_extra_1.default.writeFile(TOKEN_PATH, token, 'utf-8');
            console.log(`[AuthManager] Successfully saved new access token to ${TOKEN_PATH}.`);
        }
        catch (error) {
            console.error('[AuthManager] Failed to save access token:', error);
            throw new Error('Could not save access token.');
        }
    }
    async logout() {
        try {
            await fs_extra_1.default.remove(TOKEN_PATH);
            console.log(`[AuthManager] Successfully removed token file: ${TOKEN_PATH}`);
        }
        catch (error) {
            console.error('[AuthManager] Failed to remove access token file:', error);
            throw new Error('Could not remove access token file.');
        }
    }
}
exports.authManager = new AuthManager();
