import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigSetting } from './entities/config_setting.entity';

@Injectable()
export class ConfigSettingService {
  constructor(
    @InjectRepository(ConfigSetting)
    private configSettingRepository: Repository<ConfigSetting>,
  ) {}

  async getSettingByKey(key: string) {
    try {
      const setting = await this.configSettingRepository
        .createQueryBuilder('config_setting')
        .where('config_setting.setting_key = :key', { key })
        .getOne();

      return {
        success: true,
        data: setting,
      };
    } catch (error: any) {
      return {
        success: false,
        error: error.message,
      };
    }
  }

  async getAllSettings() {
    try {
      const settings = await this.configSettingRepository
        .createQueryBuilder('config_setting')
        .getMany();

      return {
        success: true,
        data: settings,
      };
    } catch (error: any) {
      return {
        success: false,
        error: error.message,
      };
    }
  }

  async createOrUpdateSetting(
    setting_key: string,
    setting_value: string,
    description?: string,
  ) {
    try {
      const existingSetting = await this.configSettingRepository
        .createQueryBuilder('config_setting')
        .where('config_setting.setting_key = :setting_key', { setting_key })
        .getOne();

      if (existingSetting) {
        await this.configSettingRepository
          .createQueryBuilder()
          .update(ConfigSetting)
          .set({ setting_value, description, updated_at: new Date() })
          .where('setting_key = :setting_key', { setting_key })
          .execute();

        return {
          success: true,
          message: 'Setting updated successfully',
        };
      } else {
        await this.configSettingRepository
          .createQueryBuilder()
          .insert()
          .into(ConfigSetting)
          .values({ setting_key, setting_value, description })
          .execute();

        return {
          success: true,
          message: 'Setting created successfully',
        };
      }
    } catch (error: any) {
      return {
        success: false,
        error: error.message,
      };
    }
  }

  async deleteSetting(setting_key: string) {
    try {
      await this.configSettingRepository
        .createQueryBuilder()
        .delete()
        .from(ConfigSetting)
        .where('setting_key = :setting_key', { setting_key })
        .execute();

      return {
        success: true,
        message: 'Setting deleted successfully',
      };
    } catch (error: any) {
      return {
        success: false,
        error: error.message,
      };
    }
  }

  async getCvLimitFree(): Promise<number> {
    const result = await this.getSettingByKey('cv_limit_free');
    if (result.success && result.data) {
      return parseInt(result.data.setting_value) || 100;
    }
    return 100; // default value
  }
}
