import { Injectable } from '@nestjs/common';
import { Server } from 'socket.io';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entities/user.entity';
import { Order } from '../entities/order.entity';
import { OrderItem } from '../entities/order-item.entity';

@Injectable()
export class NotificationService {
  private io: Server;

  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    @InjectRepository(Order)
    private orderRepository: Repository<Order>,
    @InjectRepository(OrderItem)
    private orderItemRepository: Repository<OrderItem>,
  ) {}

  setSocketServer(io: Server) {
    this.io = io;
  }

  async notifyOrderStatusChange(orderId: string, newStatus: string) {
    const order = await this.orderRepository.findOne({
      where: { id: orderId },
      relations: ['customer'],
    });

    if (!order) return;

    this.io.to(order.customer.id).emit('order_status_updated', {
      orderId,
      newStatus,
      timestamp: new Date().toISOString(),
    });
  }

  async notifyProductionProgress(orderItemId: string, progress: number) {
    const orderItem = await this.orderItemRepository.findOne({
      where: { id: orderItemId },
      relations: ['order', 'order.customer'],
    });

    if (!orderItem) return;

    this.io.to(orderItem.order.customer.id).emit('production_progress', {
      orderItemId,
      progress,
      timestamp: new Date().toISOString(),
    });
  }

  async notifyLowStock(materialId: string, threshold: number) {
    const users = await this.userRepository.find({
      relations: ['role'],
      where: { role: { name: 'manager' } },
    });

    users.forEach(user => {
      this.io.to(user.id).emit('low_stock_alert', {
        materialId,
        threshold,
        timestamp: new Date().toISOString(),
      });
    });
  }

  async notifyMachineMaintenance(productionLineId: string, machineId: string) {
    const users = await this.userRepository.find({
      relations: ['role'],
      where: { role: { name: 'manager' } },
    });

    users.forEach(user => {
      this.io.to(user.id).emit('maintenance_alert', {
        productionLineId,
        machineId,
        timestamp: new Date().toISOString(),
      });
    });
  }
}
