/**
 * Datadog Logs Client
 *
 * Logs API client for Datadog integration.
 *
 * @module integrations/siem/datadog
 */
import { logger } from "../../logger.js";
import { formatForDatadog } from "./format.js";
/**
 * Datadog site to API endpoint mapping
 */
const DATADOG_ENDPOINTS = {
    "datadoghq.com": "https://http-intake.logs.datadoghq.com",
    "us3.datadoghq.com": "https://http-intake.logs.us3.datadoghq.com",
    "us5.datadoghq.com": "https://http-intake.logs.us5.datadoghq.com",
    "datadoghq.eu": "https://http-intake.logs.datadoghq.eu",
    "ap1.datadoghq.com": "https://http-intake.logs.ap1.datadoghq.com",
    "ddog-gov.com": "https://http-intake.logs.ddog-gov.com",
};
/**
 * Datadog Logs API client
 */
export class DatadogClient {
    provider = "datadog";
    config;
    endpoint;
    constructor(config) {
        this.config = config;
        const site = config.options?.site || "datadoghq.com";
        this.endpoint = DATADOG_ENDPOINTS[site] || DATADOG_ENDPOINTS["datadoghq.com"];
    }
    /**
     * Test connection to Datadog
     */
    async testConnection() {
        const startTime = Date.now();
        try {
            // Datadog validates the API key on first request
            const testEvent = {
                timestamp: new Date().toISOString(),
                eventType: "scan.started",
                severity: "informational",
                project: "test",
                message: "Vaspera connection test",
                source: "vaspera",
                data: { test: true },
            };
            const result = await this.sendEvent(testEvent);
            return {
                success: result.success,
                provider: "datadog",
                endpoint: this.endpoint,
                latencyMs: Date.now() - startTime,
                error: result.error,
                details: {
                    site: this.config.options?.site || "datadoghq.com",
                    service: this.config.options?.service,
                },
            };
        }
        catch (error) {
            return {
                success: false,
                provider: "datadog",
                endpoint: this.endpoint,
                latencyMs: Date.now() - startTime,
                error: error instanceof Error ? error.message : String(error),
            };
        }
    }
    /**
     * Send a single event to Datadog
     */
    async sendEvent(event) {
        const timestamp = new Date().toISOString();
        try {
            const payload = formatForDatadog(event, {
                service: this.config.options?.service,
                env: this.config.options?.env,
                tags: this.config.options?.tags,
            });
            const response = await fetch(`${this.endpoint}/api/v2/logs`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "DD-API-KEY": this.config.token,
                },
                body: JSON.stringify([payload]),
                signal: AbortSignal.timeout(30000),
            });
            if (response.ok || response.status === 202) {
                logger.debug("siem.datadog.event_sent", {
                    eventType: event.eventType,
                });
                return {
                    success: true,
                    timestamp,
                };
            }
            const errorText = await response.text();
            logger.warn("siem.datadog.send_failed", {
                status: response.status,
                error: errorText,
            });
            return {
                success: false,
                timestamp,
                error: `HTTP ${response.status}: ${errorText}`,
            };
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            logger.error("siem.datadog.send_error", { error: errorMessage });
            return {
                success: false,
                timestamp,
                error: errorMessage,
            };
        }
    }
    /**
     * Send multiple events in batch
     */
    async sendEvents(events) {
        if (events.length === 0) {
            return {
                success: true,
                totalEvents: 0,
                successCount: 0,
                failureCount: 0,
            };
        }
        try {
            const payloads = events.map((event) => formatForDatadog(event, {
                service: this.config.options?.service,
                env: this.config.options?.env,
                tags: this.config.options?.tags,
            }));
            const response = await fetch(`${this.endpoint}/api/v2/logs`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "DD-API-KEY": this.config.token,
                },
                body: JSON.stringify(payloads),
                signal: AbortSignal.timeout(60000),
            });
            if (response.ok || response.status === 202) {
                logger.info("siem.datadog.batch_sent", {
                    eventCount: events.length,
                });
                return {
                    success: true,
                    totalEvents: events.length,
                    successCount: events.length,
                    failureCount: 0,
                };
            }
            const errorText = await response.text();
            logger.warn("siem.datadog.batch_failed", {
                status: response.status,
                error: errorText,
                eventCount: events.length,
            });
            return {
                success: false,
                totalEvents: events.length,
                successCount: 0,
                failureCount: events.length,
                errors: [{ index: 0, error: `HTTP ${response.status}: ${errorText}` }],
            };
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            logger.error("siem.datadog.batch_error", { error: errorMessage });
            return {
                success: false,
                totalEvents: events.length,
                successCount: 0,
                failureCount: events.length,
                errors: [{ index: 0, error: errorMessage }],
            };
        }
    }
    /**
     * Close connection
     */
    async close() {
        // No persistent connection to close for Datadog API
    }
}
/**
 * Create a Datadog client from configuration
 */
export function createDatadogClient(config) {
    const site = config.site || "datadoghq.com";
    return new DatadogClient({
        provider: "datadog",
        enabled: true,
        endpoint: DATADOG_ENDPOINTS[site] || DATADOG_ENDPOINTS["datadoghq.com"],
        token: config.apiKey,
        options: {
            site,
            service: config.service || "vaspera-hardening",
            env: config.env,
            tags: config.tags,
        },
    });
}
//# sourceMappingURL=datadog.js.map