import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../../../database/entities/user.entity';

@Injectable()
export class DashboardService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  async getStats() {
    // Get basic user stats
    const totalUsers = await this.userRepository.count();
    const activeUsers = await this.userRepository.count({
      where: { emailVerified: true },
    });

    // Get family and children counts
    const familyCountsRaw = await this.userRepository.query(
      `SELECT COUNT(DISTINCT family_id) as count FROM family_members`,
    );
    const totalFamilies = parseInt(familyCountsRaw[0]?.count || '0', 10);

    const childrenCountsRaw = await this.userRepository.query(
      `SELECT COUNT(*) as count FROM children`,
    );
    const totalChildren = parseInt(childrenCountsRaw[0]?.count || '0', 10);

    // Get activities count
    const activitiesCountRaw = await this.userRepository.query(
      `SELECT COUNT(*) as count FROM activities`,
    );
    const activitiesLogged = parseInt(activitiesCountRaw[0]?.count || '0', 10);

    // Get AI queries count
    const aiQueriesRaw = await this.userRepository.query(
      `SELECT COUNT(*) as count FROM ai_conversations`,
    );
    const aiQueriesTotal = parseInt(aiQueriesRaw[0]?.count || '0', 10);

    return {
      totalUsers,
      activeUsers,
      totalFamilies,
      totalChildren,
      activitiesLogged,
      aiQueriesTotal,
      systemStatus: 'healthy',
    };
  }

  async getActivityDistribution() {
    const activityDistributionRaw = await this.userRepository.query(
      `SELECT type, COUNT(*) as count FROM activities GROUP BY type ORDER BY count DESC`,
    );

    const colorMap: Record<string, string> = {
      feeding: '#FF8B7D',
      sleep: '#FFB5A0',
      diaper: '#FFD4CC',
      growth: '#81C784',
      medicine: '#FFB74D',
      activity: '#64B5F6',
    };

    return activityDistributionRaw.map((item: any) => ({
      name: item.type.charAt(0).toUpperCase() + item.type.slice(1),
      value: parseInt(item.count, 10),
      color: colorMap[item.type] || '#9E9E9E',
    }));
  }
}
