"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var GrafanaConfigService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.GrafanaConfigService = void 0;
const common_1 = require("@nestjs/common");
const config_1 = require("@nestjs/config");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const cluster_entity_1 = require("../../infrastructure/clusters/entities/cluster.entity");
const nip_hostname_util_1 = require("../../dns/utils/nip-hostname.util");
/**
 * Service for retrieving Grafana configuration and credentials
 * This service breaks the circular dependency by directly querying the clusters table
 * instead of depending on ObservabilityClusterService
 */
let GrafanaConfigService = GrafanaConfigService_1 = class GrafanaConfigService {
    constructor(clusterRepository, configService) {
        this.clusterRepository = clusterRepository;
        this.configService = configService;
        this.logger = new common_1.Logger(GrafanaConfigService_1.name);
    }
    /**
     * Get Grafana URL and credentials from observability cluster metadata
     * @returns Grafana endpoint URL, username, and admin password
     */
    async getGrafanaCredentials() {
        const obsCluster = await this.getObservabilityCluster();
        if (!obsCluster) {
            throw new Error('No observability cluster found - cannot manage Grafana datasources');
        }
        // Get Grafana endpoint and password from cluster metadata
        const endpoints = obsCluster.metadata?.observabilityStack?.endpoints;
        const passwords = obsCluster.metadata?.observabilityStack?.passwords;
        // PRIORITY 1: Try metadata first (for API-created clusters)
        if (endpoints?.grafana && passwords?.grafana) {
            return {
                url: endpoints.grafana,
                username: 'admin', // API-created clusters always use 'admin'
                password: passwords.grafana,
            };
        }
        // PRIORITY 2: Try environment variables (complete configuration)
        const envGrafanaUrl = this.configService.get('GRAFANA_URL');
        const envGrafanaUsername = this.configService.get('GRAFANA_ADMIN_USERNAME');
        const envGrafanaPassword = this.configService.get('GRAFANA_ADMIN_PASSWORD');
        // If GRAFANA_URL is provided, use env vars for complete configuration
        if (envGrafanaUrl) {
            this.logger.log('Observability cluster metadata missing. Using GRAFANA_URL from environment variables.');
            // Validate URL format
            if (!envGrafanaUrl.startsWith('http://') &&
                !envGrafanaUrl.startsWith('https://')) {
                throw new Error('GRAFANA_URL must start with http:// or https://. ' +
                    `Received: ${envGrafanaUrl}`);
            }
            if (!envGrafanaPassword) {
                throw new Error('GRAFANA_ADMIN_PASSWORD environment variable not set. ' +
                    'This is required when using GRAFANA_URL. ' +
                    'Please set this variable and restart the application.');
            }
            const username = envGrafanaUsername || 'admin'; // Default to 'admin' if not specified
            this.logger.log(`Using environment variables: ${envGrafanaUrl} (username: ${username})`);
            return {
                url: envGrafanaUrl,
                username,
                password: envGrafanaPassword,
            };
        }
        // PRIORITY 3: FALLBACK - Construct URL from cluster IP + use env vars for credentials
        this.logger.warn('Observability cluster metadata missing Grafana credentials. ' +
            'Using fallback: cluster IP + environment variables for credentials');
        if (!obsCluster.masterIpAddress) {
            throw new Error('Observability cluster missing master IP address. ' +
                'Cannot construct Grafana endpoint URL. ' +
                'Please set GRAFANA_URL environment variable or ensure cluster has masterIpAddress.');
        }
        if (!envGrafanaPassword) {
            throw new Error('GRAFANA_ADMIN_PASSWORD environment variable not set. ' +
                'This is required for CLI-created observability clusters. ' +
                'Please set this variable and restart the application.');
        }
        const grafanaUrl = `http://${(0, nip_hostname_util_1.buildSystemNipHostname)('grafana', obsCluster.masterIpAddress, obsCluster.nipHostnameToken)}`;
        const username = envGrafanaUsername || 'admin'; // Default to 'admin' if not specified
        this.logger.log(`Using fallback credentials: ${grafanaUrl} (username: ${username}, password from env)`);
        return {
            url: grafanaUrl,
            username,
            password: envGrafanaPassword,
        };
    }
    /**
     * Get the observability cluster entity
     * @returns ObservabilityCluster entity or null if not found
     */
    async getObservabilityCluster() {
        try {
            const obsCluster = await this.clusterRepository.findOne({
                where: {
                    clusterType: cluster_entity_1.ClusterType.OBSERVABILITY,
                    status: cluster_entity_1.ClusterStatus.READY,
                },
                order: { createdAt: 'DESC' },
            });
            if (!obsCluster) {
                this.logger.warn('No READY observability cluster found in database');
                return null;
            }
            this.logger.log(`Found observability cluster: ${obsCluster.name} (${obsCluster.id})`);
            return obsCluster;
        }
        catch (error) {
            this.logger.error(`Error retrieving observability cluster: ${error.message}`, error.stack);
            return null;
        }
    }
    /**
     * Get Grafana endpoint URL
     * @returns Grafana HTTP endpoint (e.g., "http://1.2.3.4:30300")
     */
    async getGrafanaEndpoint() {
        try {
            const credentials = await this.getGrafanaCredentials();
            return credentials.url;
        }
        catch (error) {
            this.logger.warn(`Failed to get Grafana endpoint: ${error.message}`);
            return null;
        }
    }
    /**
     * Get Grafana admin password
     * @returns Grafana admin password
     */
    async getGrafanaPassword() {
        try {
            const credentials = await this.getGrafanaCredentials();
            return credentials.password;
        }
        catch (error) {
            this.logger.warn(`Failed to get Grafana password: ${error.message}`);
            return null;
        }
    }
    /**
     * Get Basic Auth header for Grafana API
     * @returns Base64 encoded Basic Auth credentials
     */
    async getGrafanaAuthHeader() {
        try {
            const credentials = await this.getGrafanaCredentials();
            const auth = Buffer.from(`admin:${credentials.password}`).toString('base64');
            return `Basic ${auth}`;
        }
        catch (error) {
            this.logger.warn(`Failed to get Grafana auth header: ${error.message}`);
            return null;
        }
    }
};
exports.GrafanaConfigService = GrafanaConfigService;
exports.GrafanaConfigService = GrafanaConfigService = GrafanaConfigService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(cluster_entity_1.ClusterEntity)),
    __metadata("design:paramtypes", [typeorm_2.Repository,
        config_1.ConfigService])
], GrafanaConfigService);
