import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

export interface LeaderboardEntry {
  rank: number;
  userId: bigint;
  username: string;
  score: number;
  teamCount?: number;
  plantingCount?: number;
}

export interface LeaderboardData {
  type: string;
  period: string;
  entries: LeaderboardEntry[];
  generatedAt: Date;
}

@Injectable()
export class LeaderboardServiceClient {
  private readonly logger = new Logger(LeaderboardServiceClient.name);
  private readonly baseUrl: string;

  constructor(private readonly configService: ConfigService) {
    this.baseUrl = this.configService.get<string>(
      'LEADERBOARD_SERVICE_URL',
      'http://localhost:3007',
    );
  }

  async getDailyLeaderboard(date?: Date): Promise<LeaderboardData> {
    // In production, this would make an HTTP call to leaderboard-service
    this.logger.debug(`Fetching daily leaderboard from ${this.baseUrl}`);

    // Mock data for development
    return {
      type: 'DAILY',
      period: (date || new Date()).toISOString().split('T')[0],
      entries: [],
      generatedAt: new Date(),
    };
  }

  async getWeeklyLeaderboard(weekKey?: string): Promise<LeaderboardData> {
    this.logger.debug(`Fetching weekly leaderboard from ${this.baseUrl}`);

    return {
      type: 'WEEKLY',
      period: weekKey || this.getCurrentWeekKey(),
      entries: [],
      generatedAt: new Date(),
    };
  }

  async getMonthlyLeaderboard(monthKey?: string): Promise<LeaderboardData> {
    this.logger.debug(`Fetching monthly leaderboard from ${this.baseUrl}`);

    return {
      type: 'MONTHLY',
      period: monthKey || this.getCurrentMonthKey(),
      entries: [],
      generatedAt: new Date(),
    };
  }

  async getTopByRegion(
    regionCode: string,
    limit: number = 10,
  ): Promise<LeaderboardEntry[]> {
    this.logger.debug(
      `Fetching top ${limit} for region ${regionCode} from ${this.baseUrl}`,
    );

    return [];
  }

  private getCurrentWeekKey(): string {
    const now = new Date();
    const year = now.getFullYear();
    const weekNumber = Math.ceil(
      ((now.getTime() - new Date(year, 0, 1).getTime()) / 86400000 +
        new Date(year, 0, 1).getDay() +
        1) /
        7,
    );
    return `${year}-W${weekNumber.toString().padStart(2, '0')}`;
  }

  private getCurrentMonthKey(): string {
    const now = new Date();
    return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}`;
  }
}
