import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { NotificationEvent } from './entities/notification-event.entity';
import { WhatsappTemplate } from './entities/whatsapp-template.entity';

@Injectable()
export class WhatsAppNotificationService {
  constructor(
    @InjectRepository(NotificationEvent)
    private notificationEventRepository: Repository<NotificationEvent>,
    @InjectRepository(WhatsappTemplate)
    private whatsappTemplateRepository: Repository<WhatsappTemplate>,
  ) {}

  /**
   * Creates a notification event.
   * Does NOT check business logic, just inserts.
   */
  async createEvent(
    templateName: string,
    recipientUserId: number,
    referenceType: 'job_post' | 'job_application' | 'company',
    referenceId: number,
    payload: any,
  ): Promise<void> {
    console.log(
      `[WhatsAppNotificationService] Attempting to create event for template: '${templateName}'`,
    );

    if (!templateName) {
      console.error('[WhatsAppNotificationService] Template name is empty');
      return;
    }

    // 1. Resolve template ID from name (optional optimization: cache this)
    const template = await this.whatsappTemplateRepository.findOne({
      where: { name: templateName, is_active: true },
    });

    if (!template) {
      console.warn(
        `[WhatsAppNotificationService] WhatsApp template '${templateName}' not found or inactive.`,
      );
      return;
    }

    console.log(
      `[WhatsAppNotificationService] Found template '${templateName}' (ID: ${template.id}). Creating event...`,
    );

    // 2. Insert event
    const event = new NotificationEvent();
    event.template_id = template.id;
    event.recipient_user_id = recipientUserId;
    event.reference_type = referenceType;
    event.reference_id = referenceId;
    event.payload = payload;
    event.status = 'pending';

    const savedEvent = await this.notificationEventRepository.save(event);
    console.log(
      `[WhatsAppNotificationService] Event created successfully. ID: ${savedEvent.id}`,
    );
  }
}
