// server/src/user-setting/user-setting.service.ts
import { Injectable, OnModuleInit, Logger } from '@nestjs/common'; // Added OnModuleInit, Logger
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserSetting } from './user-setting.entity';
import { UpdateUserSettingDto } from './dto/update-user-setting.dto'; // Removed CreateUserSettingDto
import { DEFAULT_SETTINGS } from '../defaults'; // Corrected import path

@Injectable()
export class UserSettingService implements OnModuleInit {
  private readonly logger = new Logger(UserSettingService.name);

  constructor(
    @InjectRepository(UserSetting)
    private userSettingRepository: Repository<UserSetting>,
  ) { }

  async onModuleInit() {
    await this.initializeGlobalSettings();
  }

  private async initializeGlobalSettings() {
    
    let globalSetting = await this.userSettingRepository.findOne({
      where: { isGlobal: true },
    });

    if (globalSetting) {
      this.logger.log('Global settings already initialized.');
      return;
    }

    
    const legacySystemSetting = await this.userSettingRepository.findOne({
      where: { userId: 'system' },
    });

    if (legacySystemSetting) {
      this.logger.log('Migrating legacy system settings to new global format...');
      legacySystemSetting.isGlobal = true;
      legacySystemSetting.userId = null as any; // Clear the old system userId
      await this.userSettingRepository.save(legacySystemSetting);
      this.logger.log('Migration complete.');
    } else {
      
      this.logger.log('No global settings found. Creating initial global settings...');
      const newGlobalSetting = this.userSettingRepository.create({
        isGlobal: true,
        userId: null as any,
        ...DEFAULT_SETTINGS,
      });
      await this.userSettingRepository.save(newGlobalSetting);
      this.logger.log('Initial global settings created.');
    }
  }

  async findOrCreate(userId: string): Promise<UserSetting> {
    let userSetting = await this.userSettingRepository.findOne({
      where: { userId },
    });

    if (!userSetting) {
      const newSetting = this.userSettingRepository.create({
        userId,
        ...DEFAULT_SETTINGS, // Use default frontend settings as initial backend settings
      });
      userSetting = await this.userSettingRepository.save(newSetting);
    }
    return userSetting;
  }

  async update(
    userId: string,
    updateUserSettingDto: UpdateUserSettingDto,
  ): Promise<UserSetting> {
    const existingSetting = await this.userSettingRepository.findOne({
      where: { userId },
    });

    if (!existingSetting) {
      // If no setting exists, create one with default values and then apply updates
      const newSetting = this.userSettingRepository.create({
        userId,
        ...DEFAULT_SETTINGS,
        ...updateUserSettingDto,
      });
      return this.userSettingRepository.save(newSetting);
    }

    const updated = this.userSettingRepository.merge(
      existingSetting,
      updateUserSettingDto,
    );
    return this.userSettingRepository.save(updated);
  }

  async updateVisionModel(
    userId: string,
    visionModelId: string,
  ): Promise<UserSetting> {
    const settings = await this.findOrCreate(userId);
    settings.defaultVisionModelId = visionModelId;
    return this.userSettingRepository.save(settings);
  }

  async getVisionModelId(userId: string): Promise<string | null> {
    const settings = await this.userSettingRepository.findOne({
      where: { userId },
    });
    return settings?.defaultVisionModelId || null;
  }

  async updateLanguage(userId: string, language: string): Promise<UserSetting> {
    console.log('=== updateLanguage Debug ===');
    console.log('userId:', userId);
    console.log('New language:', language);
    const settings = await this.findOrCreate(userId);
    console.log('Settings before update:', settings);
    settings.language = language;
    const result = await this.userSettingRepository.save(settings);
    console.log('Result after update:', result);
    console.log('===============================');
    return result;
  }

  async getLanguage(userId: string): Promise<string> {
    const settings = await this.userSettingRepository.findOne({
      where: { userId },
    });
    console.log('=== getLanguage Debug ===');
    console.log('userId:', userId);
    console.log('settings:', settings);
    console.log('settings.language:', settings?.language);
    console.log('Returned language:', settings?.language || 'zh');
    console.log('============================');
    return settings?.language || 'zh';
  }

  
  async getGlobalSettings(): Promise<UserSetting> {
    const globalSetting = await this.userSettingRepository.findOne({
      where: { isGlobal: true },
    });

    if (!globalSetting) {
      
      await this.initializeGlobalSettings();
      return this.getGlobalSettings();
    }
    return globalSetting;
  }

  
  async updateGlobalSettings(
    updateUserSettingDto: UpdateUserSettingDto,
  ): Promise<UserSetting> {
    const globalSetting = await this.getGlobalSettings();
    const updated = this.userSettingRepository.merge(
      globalSetting,
      updateUserSettingDto,
    );
    return this.userSettingRepository.save(updated);
  }
}

