import { env } from '../config/env';
import { logger } from '../utils/logger';
import { rocketchatClient } from './rocketchat.client';

class RocketChatWebhookService {
  private get enabled(): boolean {
    return env.ENABLE_CHAT === 'true';
  }

  /**
   * Post a notification to a Rocket.Chat channel.
   * Silently fails if chat is disabled or RC is unreachable.
   */
  private async notify(channel: string, text: string, color?: string): Promise<void> {
    if (!this.enabled) return;
    try {
      await rocketchatClient.postMessage(channel, text, 'Changemaker Bot');
    } catch (err) {
      logger.debug(`RC notification to ${channel} failed (non-critical):`, err);
    }
  }

  // --- Event Formatters ---

  async onShiftSignup(data: {
    userName: string;
    shiftTitle: string;
    shiftDate: string;
  }): Promise<void> {
    const text = `:calendar: **${data.userName}** signed up for shift: *${data.shiftTitle}* (${data.shiftDate})`;
    await this.notify('#shifts', text, '#27ae60');
  }

  async onShiftCancellation(data: {
    userName: string;
    shiftTitle: string;
    shiftDate: string;
  }): Promise<void> {
    const text = `:x: **${data.userName}** cancelled signup for shift: *${data.shiftTitle}* (${data.shiftDate})`;
    await this.notify('#shifts', text, '#e74c3c');
  }

  async onCanvassSessionCompleted(data: {
    userName: string;
    visitCount: number;
    cutName?: string;
  }): Promise<void> {
    const location = data.cutName ? ` in ${data.cutName}` : '';
    const text = `:door: **${data.userName}** completed ${data.visitCount} visits${location}`;
    await this.notify('#canvassing', text, '#3498db');
  }

  async onCampaignResponseSubmitted(data: {
    campaignTitle: string;
    representativeName: string;
  }): Promise<void> {
    const text = `:mega: New response submitted for campaign *${data.campaignTitle}* from **${data.representativeName}**`;
    await this.notify('#campaigns', text, '#9b59b6');
  }

  async onCampaignPublished(data: {
    campaignTitle: string;
    campaignSlug: string;
  }): Promise<void> {
    const text = `:newspaper: Campaign published: *${data.campaignTitle}* → /campaigns/${data.campaignSlug}`;
    await this.notify('#campaigns', text, '#27ae60');
  }

  async onDonationReceived(data: {
    donorName: string;
    amount: string;
  }): Promise<void> {
    const text = `:money_with_wings: **${data.donorName}** donated **$${data.amount}**`;
    await this.notify('#campaigns', text, '#f1c40f');
  }

  async onSubscriptionActivated(data: {
    userName: string;
    planName: string;
  }): Promise<void> {
    const text = `:star: **${data.userName}** subscribed to *${data.planName}*`;
    await this.notify('#campaigns', text, '#9b59b6');
  }

  async onSmsEscalation(data: {
    phone: string;
    responseType: string;
    body: string;
  }): Promise<void> {
    const preview = data.body.length > 100 ? data.body.slice(0, 100) + '...' : data.body;
    const text = `:warning: SMS ${data.responseType} from ${data.phone}: "${preview}"`;
    await this.notify('#campaigns', text, '#e74c3c');
  }

  async onUserApproved(data: {
    userName: string;
    role: string;
  }): Promise<void> {
    const text = `:white_check_mark: User approved: **${data.userName}** (${data.role})`;
    await this.notify('#campaigns', text, '#2ecc71');
  }

  async onVideoPublished(data: {
    videoTitle: string;
  }): Promise<void> {
    const text = `:film_projector: New video published: *${data.videoTitle}*`;
    await this.notify('#campaigns', text, '#3498db');
  }

  async onTicketedEventPublished(data: {
    eventTitle: string;
    eventDate: string;
  }): Promise<void> {
    const text = `:ticket: Event published: *${data.eventTitle}* (${data.eventDate})`;
    await this.notify('#campaigns', text, '#e67e22');
  }

  /**
   * Ensure default notification channels exist in Rocket.Chat.
   * Called during service startup.
   */
  async setupChannels(): Promise<void> {
    if (!this.enabled) return;
    try {
      await rocketchatClient.ensureChannel('shifts', 'Shift coordination and updates');
      await rocketchatClient.ensureChannel('canvassing', 'Canvass activity and updates');
      await rocketchatClient.ensureChannel('campaigns', 'Campaign activity and responses');
      logger.info('RC notification channels verified');
    } catch (err) {
      logger.warn('RC channel setup failed (will retry on next notification):', err);
    }
  }
}

export const rocketchatWebhookService = new RocketChatWebhookService();
