import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { NotificationsConfig } from '../../entities/notifications-config.entity';
import { UpdateConfigDto } from './dto/update-config.dto';

@Injectable()
export class NotificationsService {
  constructor(
    @InjectRepository(NotificationsConfig)
    private configRepository: Repository<NotificationsConfig>,
  ) {}

  async getConfig(licenseId: string): Promise<NotificationsConfig> {
    let config = await this.configRepository.findOne({
      where: { license_id: licenseId },
    });

    // Create default config if not exists
    if (!config) {
      config = this.configRepository.create({
        license_id: licenseId,
        discord_enabled: false,
        discord_webhook_url: null,
        pushbullet_enabled: false,
        pushbullet_api_key: null,
        email_alerts_enabled: true,
        notify_wipe_start: true,
        notify_wipe_complete: true,
        notify_wipe_failed: true,
        notify_server_crash: true,
        notify_server_offline: true,
        notify_store_purchase: true,
        notify_player_report: false,
      });

      config = await this.configRepository.save(config);
    }

    return config;
  }

  async updateConfig(
    licenseId: string,
    dto: UpdateConfigDto,
  ): Promise<NotificationsConfig> {
    // Ensure config exists first
    let config = await this.getConfig(licenseId);

    // Update fields
    Object.assign(config, dto);

    return await this.configRepository.save(config);
  }
}
