import { Injectable } from '@nestjs/common';
import { PrismaService } from '../database/prisma.service';
import { ILeaderboardConfigRepository } from '../../domain/repositories/leaderboard-config.repository.interface';
import { LeaderboardConfig } from '../../domain/aggregates/leaderboard-config/leaderboard-config.aggregate';

@Injectable()
export class LeaderboardConfigRepositoryImpl implements ILeaderboardConfigRepository {
  constructor(private readonly prisma: PrismaService) {}

  async save(config: LeaderboardConfig): Promise<void> {
    const data = {
      configKey: config.configKey,
      dailyEnabled: config.dailyEnabled,
      weeklyEnabled: config.weeklyEnabled,
      monthlyEnabled: config.monthlyEnabled,
      virtualRankingEnabled: config.virtualRankingEnabled,
      virtualAccountCount: config.virtualAccountCount,
      displayLimit: config.displayLimit,
      refreshIntervalMinutes: config.refreshIntervalMinutes,
    };

    if (config.id) {
      await this.prisma.leaderboardConfig.update({
        where: { id: config.id },
        data,
      });
    } else {
      const result = await this.prisma.leaderboardConfig.upsert({
        where: { configKey: config.configKey },
        update: data,
        create: data,
      });
      config.setId(result.id);
    }
  }

  async findByKey(configKey: string): Promise<LeaderboardConfig | null> {
    const record = await this.prisma.leaderboardConfig.findUnique({
      where: { configKey },
    });

    if (!record) return null;
    return this.toDomain(record);
  }

  async getGlobalConfig(): Promise<LeaderboardConfig> {
    let record = await this.prisma.leaderboardConfig.findUnique({
      where: { configKey: 'GLOBAL' },
    });

    if (!record) {
      // 创建默认配置
      record = await this.prisma.leaderboardConfig.create({
        data: {
          configKey: 'GLOBAL',
          dailyEnabled: true,
          weeklyEnabled: true,
          monthlyEnabled: true,
          virtualRankingEnabled: false,
          virtualAccountCount: 0,
          displayLimit: 30,
          refreshIntervalMinutes: 5,
        },
      });
    }

    return this.toDomain(record);
  }

  private toDomain(record: any): LeaderboardConfig {
    return LeaderboardConfig.reconstitute({
      id: record.id,
      configKey: record.configKey,
      dailyEnabled: record.dailyEnabled,
      weeklyEnabled: record.weeklyEnabled,
      monthlyEnabled: record.monthlyEnabled,
      virtualRankingEnabled: record.virtualRankingEnabled,
      virtualAccountCount: record.virtualAccountCount,
      displayLimit: record.displayLimit,
      refreshIntervalMinutes: record.refreshIntervalMinutes,
    });
  }
}
