import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserNotificationPreferences, NotificationChannel, DEFAULT_ENABLED_EVENT_TYPES } from '../../entities/user-notification-preferences.entity';
import { Users } from '../../entities/users.entity';
import { UpdateWhatsAppPreferencesDto } from './dtos/update-whatsapp-preferences.dto';
import { UpdateNotificationPreferencesDto } from './dtos/update-notification-preferences.dto';
import { responseMessages } from 'src/messages/response-messages';

/** All event types enabled by default when user registers */


@Injectable()
export class NotificationPreferencesService {
  constructor(@InjectRepository(UserNotificationPreferences) private readonly preferencesRepo: Repository<UserNotificationPreferences>, @InjectRepository(Users) private readonly usersRepo: Repository<Users>,) { }

  /**
* Get all notification preferences for a user (one per channel).
*/
  async getPreferences(userId: string) {
    const list = await this.preferencesRepo.find({
      where: {
        user: {
          id: userId
        }
      },
      order: {
        channel: 'ASC'
      }
    });
    return list;
  }

  /**
 * Common method: update notification preferences for any channel.
 */
  async updatePreferences(authUser: any, channel: NotificationChannel, dto: UpdateNotificationPreferencesDto) {
    await this.preferencesRepo.update({
      id: channel
    }, dto);
    return;
  }

  /**
 * Create default notification preferences for a newly registered user.
 * Enables all channels with all event types.
 */
  async createDefaultPreferencesForUser(userId: string) {
    const user = await this.usersRepo.findOne({ where: { id: userId } });
    if (!user) {
      throw new HttpException(responseMessages.en.user.user_not_exists, HttpStatus.NOT_FOUND);
    }
    const channels = Object.values(NotificationChannel);
    for (const channel of channels) {
      const existing = await this.preferencesRepo.findOne({ where: { user: { id: userId }, channel } });
      if (!existing) {
        const pref = {
          user,
          channel,
          is_enabled: false,
          enabled_types: Object.values(DEFAULT_ENABLED_EVENT_TYPES)
        };
        await this.preferencesRepo.save(pref);
      }
    }
  }

  //CREATE SCRIPT FOR ALL USERS THAT ARE VERIFIED AND HAVE NOTIFICATION PREFERENCES
  async script() {
    const users = await this.usersRepo.find({ where: { is_verify_otp: true } });
    for (const user of users) {
      await this.createDefaultPreferencesForUser(user.id);
    }
    return;
  }
}
