import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Order } from '../entities/order.entity';
import { Material } from '../entities/material.entity';
import { ProductionQueue } from '../entities/production-queue.entity';

export interface DashboardStats {
  totalOrders: number;
  totalRevenue: number;
  completedOrders: number;
  pendingOrders: number;
  productionEfficiency: number;
  qualityPassRate: number;
  lowStockMaterials: {
    id: string;
    name: string;
    currentStock: number;
    threshold: number;
  }[];
}

@Injectable()
export class DashboardService {
  constructor(
    @InjectRepository(Order)
    private ordersRepository: Repository<Order>,
    @InjectRepository(Material)
    private materialsRepository: Repository<Material>,
    @InjectRepository(ProductionQueue)
    private productionQueueRepository: Repository<ProductionQueue>,
  ) {}

  async getDashboardStats(): Promise<DashboardStats> {
    const [totalOrders, totalRevenue] = await Promise.all([
      this.ordersRepository.count(),
      this.ordersRepository
        .createQueryBuilder('order')
        .select('SUM(order.totalAmount)', 'totalRevenue')
        .getRawOne(),
    ]);

    const [completedOrders, pendingOrders] = await Promise.all([
      this.ordersRepository.count({ where: { status: 'completed' } }),
      this.ordersRepository.count({ where: { status: 'pending' } }),
    ]);

    const productionEfficiency = await this.calculateProductionEfficiency();
    const qualityPassRate = await this.calculateQualityPassRate();
    const lowStockMaterials = await this.getLowStockMaterials();

    return {
      totalOrders,
      totalRevenue: totalRevenue?.totalRevenue || 0,
      completedOrders,
      pendingOrders,
      productionEfficiency,
      qualityPassRate,
      lowStockMaterials,
    };
  }

  async getRecentOrders(): Promise<any[]> {
    return this.ordersRepository
      .createQueryBuilder('order')
      .leftJoinAndSelect('order.customer', 'customer')
      .orderBy('order.createdAt', 'DESC')
      .take(10)
      .getMany();
  }

  async getProductionDetails(): Promise<any> {
    const productionQueue = await this.productionQueueRepository.find({
      relations: ['order', 'materials'],
      order: { createdAt: 'DESC' },
      take: 10,
    });

    return {
      queue: productionQueue,
      efficiency: await this.calculateProductionEfficiency(),
    };
  }

  private async calculateProductionEfficiency(): Promise<number> {
    const completed = await this.productionQueueRepository.count({
      where: { status: 'completed' },
    });

    const total = await this.productionQueueRepository.count();

    return total > 0 ? Math.round((completed / total) * 100) : 0;
  }

  private async calculateQualityPassRate(): Promise<number> {
    // For now, return a mock value. In a real implementation, this would query quality check data
    return 95; // 95% pass rate
  }

  private async getLowStockMaterials(): Promise<any[]> {
    return this.materialsRepository
      .createQueryBuilder('material')
      .where('material.currentStock < material.threshold')
      .getMany();
  }
}
