import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserSetting } from './user-setting.entity';

@Injectable()
export class UserSettingService {
  constructor(
    @InjectRepository(UserSetting)
    private userSettingRepository: Repository<UserSetting>,
  ) {}

  async getByUser(userId: string): Promise<UserSetting> {
    let setting = await this.userSettingRepository.findOne({ where: { userId } });
    if (!setting) {
      setting = this.userSettingRepository.create({ userId, language: 'zh' });
      await this.userSettingRepository.save(setting);
    }
    return setting;
  }

  async update(userId: string, language: string): Promise<UserSetting> {
    const setting = await this.getByUser(userId);
    setting.language = language;
    return this.userSettingRepository.save(setting);
  }
}
