import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { ServiceLogger } from '../logging/service-logger';
import type { DeviceInfo } from '../utils/device-info.helper';

type ErrorAlertInput = {
  source: string;
  error: unknown;
  statusCode?: number;
  method?: string;
  path?: string;
  user?: { id?: string; email?: string; role?: string };
  metadata?: Record<string, string | number | boolean | null | undefined>;
};

@Injectable()
export class SlackService {
  private static readonly ERROR_ALERT_COOLDOWN_MS = 5 * 60 * 1000;
  private static readonly LOGIN_NOTIFICATION_EXCLUDED_IPS = new Set([
    '122.170.107.160',
    '14.96.104.186',
  ]);

  private readonly logger = new ServiceLogger(SlackService.name);
  private readonly errorAlertCooldowns = new Map<string, number>();

  constructor(private readonly configService: ConfigService) {}

  async sendErrorNotification(input: ErrorAlertInput): Promise<void> {
    const webhookUrl = this.configService.get<string>('SLACK_WEBHOOK_URL');

    if (!webhookUrl) {
      this.logger.warn('slack.error_notification.skipped', {
        reason: 'SLACK_WEBHOOK_URL is not configured',
      });
      return;
    }

    const details = this.errorDetails(input.error);
    const fingerprint = [
      input.source,
      input.statusCode ?? 'unknown',
      input.method ?? 'unknown',
      input.path ?? 'unknown',
      details.name,
      details.message,
    ].join('|');

    if (this.isErrorAlertCoolingDown(fingerprint)) {
      this.logger.warn('slack.error_notification.suppressed', {
        source: input.source,
        statusCode: input.statusCode,
        path: input.path,
      });
      return;
    }

    try {
      const lines = [
        `*Source:* ${this.safeText(input.source)}`,
        ...(input.statusCode ? [`*Status:* ${input.statusCode}`] : []),
        ...(input.method || input.path
          ? [
              `*Request:* ${this.safeText(input.method ?? 'Unknown')} ${this.safeText(input.path ?? 'Unknown')}`,
            ]
          : []),
        `*Error:* ${this.safeText(details.name)}`,
        `*Message:* ${this.safeText(details.message)}`,
        ...(details.code ? [`*Code:* \`${this.safeText(details.code)}\``] : []),
        ...(input.user?.id
          ? [`*User ID:* \`${this.safeText(input.user.id)}\``]
          : []),
        ...(input.user?.email
          ? [`*User Email:* ${this.safeText(input.user.email)}`]
          : []),
        ...(input.user?.role
          ? [`*User Role:* \`${this.safeText(input.user.role)}\``]
          : []),
        ...Object.entries(input.metadata ?? {}).flatMap(([key, value]) =>
          value === undefined || value === null
            ? []
            : [`*${this.safeText(key)}:* ${this.safeText(String(value))}`],
        ),
      ];

      const response = await fetch(webhookUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          blocks: [
            {
              type: 'header',
              text: {
                type: 'plain_text',
                text: 'IIH SEO Portal Error Alert',
                emoji: true,
              },
            },
            {
              type: 'section',
              text: { type: 'mrkdwn', text: lines.join('\n') },
            },
            {
              type: 'context',
              elements: [
                {
                  type: 'mrkdwn',
                  text: `*Time:* ${new Date().toISOString()}`,
                },
              ],
            },
          ],
        }),
      });

      if (!response.ok) {
        this.logger.error(
          'slack.error_notification.failed',
          new Error(`HTTP ${response.status}: ${response.statusText}`),
        );
        return;
      }

      this.logger.log('slack.error_notification.sent', {
        source: input.source,
        statusCode: input.statusCode,
        path: input.path,
      });
    } catch (error) {
      this.logger.error('slack.error_notification.error', error, {
        source: input.source,
        statusCode: input.statusCode,
        path: input.path,
      });
    }
  }

  async sendLoginNotification(
    user: { id: string; email: string; name: string; role: string },
    deviceInfo: DeviceInfo,
  ): Promise<void> {
    if (
      SlackService.LOGIN_NOTIFICATION_EXCLUDED_IPS.has(
        deviceInfo.ip_address,
      )
    ) {
      this.logger.log('slack.login_notification.skipped', {
        reason: 'IP address is excluded from login notifications',
        ipAddress: deviceInfo.ip_address,
        email: user.email,
      });
      return;
    }

    const webhookUrl = this.configService.get<string>('SLACK_WEBHOOK_URL');

    if (!webhookUrl) {
      this.logger.warn('slack.notification.skipped', {
        reason: 'SLACK_WEBHOOK_URL is not configured',
      });
      return;
    }

    try {
      const latitude =
        deviceInfo.lat === null ? 'Not available' : String(deviceInfo.lat);
      const longitude =
        deviceInfo.lng === null ? 'Not available' : String(deviceInfo.lng);

      const payload = {
        blocks: [
          {
            type: 'header',
            text: {
              type: 'plain_text',
              text: '🔐 New User Login Alert',
              emoji: true,
            },
          },
          {
            type: 'section',
            text: {
              type: 'mrkdwn',
              text: [
                `*User Name:* ${user.name}`,
                `*Email:* ${user.email}`,
                `*Role:* \`${user.role}\``,
                `*IP Address:* \`${deviceInfo.ip_address}\``,
                `*Hostname:* ${deviceInfo.hostname}`,
                `*Latitude:* ${latitude}`,
                `*Longitude:* ${longitude}`,
                `*Device:* ${deviceInfo.device}`,
                `*Device Type:* ${deviceInfo.deviceType}`,
                `*Browser:* ${deviceInfo.browser}`,
                `*Is robot:* ${deviceInfo.isRobot ? 'Yes' : 'No'}`,
                `*User Agent:* \`${deviceInfo.user_agent.replace(/\`/g, "'")}\``,
              ].join('\n'),
            },
          },
          {
            type: 'context',
            elements: [
              {
                type: 'mrkdwn',
                text: `*Time:* ${new Date().toISOString()} | *User ID:* \`${user.id}\``,
              },
            ],
          },
        ],
      };

      const response = await fetch(webhookUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      if (!response.ok) {
        this.logger.error(
          'slack.notification.failed',
          new Error(`HTTP ${response.status}: ${response.statusText}`),
        );
      } else {
        this.logger.log('slack.notification.sent', { email: user.email });
      }
    } catch (error) {
      this.logger.error('slack.notification.error', error);
    }
  }

  private isErrorAlertCoolingDown(fingerprint: string) {
    const now = Date.now();
    const lastSentAt = this.errorAlertCooldowns.get(fingerprint);

    if (lastSentAt && now - lastSentAt < SlackService.ERROR_ALERT_COOLDOWN_MS) {
      return true;
    }

    this.errorAlertCooldowns.set(fingerprint, now);
    return false;
  }

  private errorDetails(error: unknown) {
    if (error instanceof Error) {
      const errorWithCode = error as Error & { code?: unknown };
      return {
        name: error.name || 'Error',
        message: error.message || 'Unknown error',
        code:
          typeof errorWithCode.code === 'string' ||
          typeof errorWithCode.code === 'number'
            ? String(errorWithCode.code)
            : undefined,
      };
    }

    return { name: 'UnknownError', message: String(error) };
  }

  private safeText(value: string) {
    return value
      .replace(/[\`*_~]/g, "'")
      .replace(
        /(password|token|cookie|authorization|secret)\s*[:=]\s*[^\s,]+/gi,
        '$1=[redacted]',
      )
      .slice(0, 900);
  }
}
