/**
 * Webhook Configuration Service
 * Manages Slack, PagerDuty, and email webhook configurations
 */

export interface WebhookConfig {
  slack?: {
    webhookUrl: string;
    enabled: boolean;
    testMode: boolean;
  };
  pagerduty?: {
    integrationKey: string;
    enabled: boolean;
    testMode: boolean;
  };
  email?: {
    recipients: string[];
    enabled: boolean;
    testMode: boolean;
  };
}

export interface WebhookTestResult {
  channel: 'slack' | 'pagerduty' | 'email';
  success: boolean;
  message: string;
  timestamp: Date;
}

class WebhookConfigService {
  private config: WebhookConfig = {
    slack: {
      webhookUrl: '',
      enabled: false,
      testMode: false,
    },
    pagerduty: {
      integrationKey: '',
      enabled: false,
      testMode: false,
    },
    email: {
      recipients: [],
      enabled: false,
      testMode: false,
    },
  };

  private testResults: WebhookTestResult[] = [];

  /**
   * Get current webhook configuration
   */
  getConfig(): WebhookConfig {
    return {
      ...this.config,
      slack: this.config.slack ? { ...this.config.slack, webhookUrl: '***' } : undefined,
      pagerduty: this.config.pagerduty ? { ...this.config.pagerduty, integrationKey: '***' } : undefined,
    };
  }

  /**
   * Set Slack webhook configuration
   */
  setSlackWebhook(webhookUrl: string, enabled: boolean = true) {
    if (!webhookUrl.startsWith('https://hooks.slack.com/')) {
      throw new Error('Invalid Slack webhook URL format');
    }

    this.config.slack = {
      webhookUrl,
      enabled,
      testMode: false,
    };

    console.log('[Webhook Config] Slack webhook configured');
  }

  /**
   * Set PagerDuty integration key
   */
  setPagerDutyKey(integrationKey: string, enabled: boolean = true) {
    if (!integrationKey || integrationKey.length < 10) {
      throw new Error('Invalid PagerDuty integration key');
    }

    this.config.pagerduty = {
      integrationKey,
      enabled,
      testMode: false,
    };

    console.log('[Webhook Config] PagerDuty integration key configured');
  }

  /**
   * Set email recipients
   */
  setEmailRecipients(recipients: string[], enabled: boolean = true) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const invalidEmails = recipients.filter((email) => !emailRegex.test(email));

    if (invalidEmails.length > 0) {
      throw new Error(`Invalid email addresses: ${invalidEmails.join(', ')}`);
    }

    this.config.email = {
      recipients,
      enabled,
      testMode: false,
    };

    console.log('[Webhook Config] Email recipients configured:', recipients);
  }

  /**
   * Enable/disable Slack webhook
   */
  setSlackEnabled(enabled: boolean) {
    if (this.config.slack) {
      this.config.slack.enabled = enabled;
      console.log(`[Webhook Config] Slack webhook ${enabled ? 'enabled' : 'disabled'}`);
    }
  }

  /**
   * Enable/disable PagerDuty webhook
   */
  setPagerDutyEnabled(enabled: boolean) {
    if (this.config.pagerduty) {
      this.config.pagerduty.enabled = enabled;
      console.log(`[Webhook Config] PagerDuty webhook ${enabled ? 'enabled' : 'disabled'}`);
    }
  }

  /**
   * Enable/disable email webhook
   */
  setEmailEnabled(enabled: boolean) {
    if (this.config.email) {
      this.config.email.enabled = enabled;
      console.log(`[Webhook Config] Email webhook ${enabled ? 'enabled' : 'disabled'}`);
    }
  }

  /**
   * Test Slack webhook
   */
  async testSlackWebhook(): Promise<WebhookTestResult> {
    if (!this.config.slack?.webhookUrl) {
      return {
        channel: 'slack',
        success: false,
        message: 'Slack webhook not configured',
        timestamp: new Date(),
      };
    }

    try {
      const response = await fetch(this.config.slack.webhookUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          text: '🧪 Test Alert from CoinKrazy Monitoring System',
          attachments: [
            {
              color: '#36a64f',
              title: 'Webhook Configuration Test',
              text: 'This is a test message to verify Slack webhook connectivity.',
              fields: [
                {
                  title: 'Status',
                  value: 'Success',
                  short: true,
                },
                {
                  title: 'Timestamp',
                  value: new Date().toISOString(),
                  short: true,
                },
              ],
              footer: 'CoinKrazy Monitoring',
            },
          ],
        }),
      });

      const result: WebhookTestResult = {
        channel: 'slack',
        success: response.ok,
        message: response.ok ? 'Slack webhook test successful' : `Slack API error: ${response.statusText}`,
        timestamp: new Date(),
      };

      this.recordTestResult(result);
      return result;
    } catch (error) {
      const result: WebhookTestResult = {
        channel: 'slack',
        success: false,
        message: `Slack webhook test failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
        timestamp: new Date(),
      };

      this.recordTestResult(result);
      return result;
    }
  }

  /**
   * Test PagerDuty webhook
   */
  async testPagerDutyWebhook(): Promise<WebhookTestResult> {
    if (!this.config.pagerduty?.integrationKey) {
      return {
        channel: 'pagerduty',
        success: false,
        message: 'PagerDuty integration key not configured',
        timestamp: new Date(),
      };
    }

    try {
      const response = await fetch('https://events.pagerduty.com/v2/enqueue', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          routing_key: this.config.pagerduty.integrationKey,
          event_action: 'trigger',
          dedup_key: `webhook-test-${Date.now()}`,
          payload: {
            summary: 'CoinKrazy Monitoring - Webhook Configuration Test',
            severity: 'info',
            source: 'CoinKrazy Monitoring System',
            custom_details: {
              message: 'This is a test alert to verify PagerDuty webhook connectivity.',
              testType: 'webhook_configuration',
            },
            timestamp: new Date().toISOString(),
          },
        }),
      });

      const result: WebhookTestResult = {
        channel: 'pagerduty',
        success: response.ok,
        message: response.ok ? 'PagerDuty webhook test successful' : `PagerDuty API error: ${response.statusText}`,
        timestamp: new Date(),
      };

      this.recordTestResult(result);
      return result;
    } catch (error) {
      const result: WebhookTestResult = {
        channel: 'pagerduty',
        success: false,
        message: `PagerDuty webhook test failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
        timestamp: new Date(),
      };

      this.recordTestResult(result);
      return result;
    }
  }

  /**
   * Test email webhook
   */
  async testEmailWebhook(): Promise<WebhookTestResult> {
    if (!this.config.email?.recipients || this.config.email.recipients.length === 0) {
      return {
        channel: 'email',
        success: false,
        message: 'Email recipients not configured',
        timestamp: new Date(),
      };
    }

    try {
      // In production, this would send an actual test email
      console.log('[Webhook Config] Email test would be sent to:', this.config.email.recipients);

      const result: WebhookTestResult = {
        channel: 'email',
        success: true,
        message: `Email test sent to ${this.config.email.recipients.length} recipient(s)`,
        timestamp: new Date(),
      };

      this.recordTestResult(result);
      return result;
    } catch (error) {
      const result: WebhookTestResult = {
        channel: 'email',
        success: false,
        message: `Email webhook test failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
        timestamp: new Date(),
      };

      this.recordTestResult(result);
      return result;
    }
  }

  /**
   * Test all webhooks
   */
  async testAllWebhooks(): Promise<WebhookTestResult[]> {
    const results = await Promise.all([
      this.testSlackWebhook(),
      this.testPagerDutyWebhook(),
      this.testEmailWebhook(),
    ]);

    return results;
  }

  /**
   * Record test result
   */
  private recordTestResult(result: WebhookTestResult) {
    this.testResults.push(result);

    // Keep only recent results
    if (this.testResults.length > 100) {
      this.testResults = this.testResults.slice(-100);
    }

    console.log(`[Webhook Config] Test result for ${result.channel}:`, result.message);
  }

  /**
   * Get test results
   */
  getTestResults(limit: number = 50): WebhookTestResult[] {
    return this.testResults.slice(-limit);
  }

  /**
   * Get test results by channel
   */
  getTestResultsByChannel(channel: 'slack' | 'pagerduty' | 'email', limit: number = 20): WebhookTestResult[] {
    return this.testResults.filter((r) => r.channel === channel).slice(-limit);
  }

  /**
   * Get latest test result for each channel
   */
  getLatestTestResults(): Record<string, WebhookTestResult | null> {
    const channels = ['slack', 'pagerduty', 'email'] as const;
    const latest: Record<string, WebhookTestResult | null> = {};

    channels.forEach((channel) => {
      const results = this.testResults.filter((r) => r.channel === channel);
      latest[channel] = results.length > 0 ? results[results.length - 1] : null;
    });

    return latest;
  }

  /**
   * Validate configuration
   */
  validate(): {
    valid: boolean;
    errors: string[];
    warnings: string[];
  } {
    const errors: string[] = [];
    const warnings: string[] = [];

    if (!this.config.slack?.webhookUrl && this.config.slack?.enabled) {
      errors.push('Slack webhook enabled but URL not configured');
    }

    if (!this.config.pagerduty?.integrationKey && this.config.pagerduty?.enabled) {
      errors.push('PagerDuty enabled but integration key not configured');
    }

    if ((!this.config.email?.recipients || this.config.email.recipients.length === 0) && this.config.email?.enabled) {
      errors.push('Email enabled but no recipients configured');
    }

    if (!this.config.slack?.enabled && !this.config.pagerduty?.enabled && !this.config.email?.enabled) {
      warnings.push('No webhook channels are enabled - alerts will not be delivered');
    }

    return {
      valid: errors.length === 0,
      errors,
      warnings,
    };
  }

  /**
   * Clear test results
   */
  clearTestResults() {
    this.testResults = [];
    console.log('[Webhook Config] Test results cleared');
  }
}

export const webhookConfigService = new WebhookConfigService();
