import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ProductionLine } from '../entities/production-line.entity';
import { CreateProductionLineDto } from '../dto/create-production-line.dto';
import { UpdateProductionLineDto } from '../dto/update-production-line.dto';

@Injectable()
export class ProductionLineService {
  constructor(
    @InjectRepository(ProductionLine)
    private productionLineRepository: Repository<ProductionLine>,
  ) {}

  async findAll(): Promise<ProductionLine[]> {
    return this.productionLineRepository.find({
      relations: ['manager', 'machines', 'orderItems'],
      order: {
        createdAt: 'DESC',
      },
    });
  }

  async findOne(id: string): Promise<ProductionLine> {
    return this.productionLineRepository.findOne({
      where: { id },
      relations: ['manager', 'machines', 'orderItems'],
    });
  }

  async create(createDto: CreateProductionLineDto): Promise<ProductionLine> {
    const productionLine = this.productionLineRepository.create(createDto);
    return this.productionLineRepository.save(productionLine);
  }

  async update(id: string, updateDto: UpdateProductionLineDto): Promise<ProductionLine> {
    await this.productionLineRepository.update(id, updateDto);
    return this.findOne(id);
  }

  async remove(id: string): Promise<void> {
    await this.productionLineRepository.delete(id);
  }

  async findByType(type: string): Promise<ProductionLine[]> {
    return this.productionLineRepository.find({
      where: { type: type as 'fabric' | 'furniture' | 'metalworks' | 'shoes' },
      relations: ['manager', 'machines'],
    });
  }

  async findByStatus(status: string): Promise<ProductionLine[]> {
    return this.productionLineRepository.find({
      where: { status: status as 'active' | 'maintenance' | 'inactive' },
      relations: ['manager', 'machines'],
    });
  }

  async getCapacityByType(type: string): Promise<number> {
    const lines = await this.findByType(type);
    return lines.reduce((total, line) => total + line.capacity, 0);
  }

  async getAvailableLines(type: string): Promise<ProductionLine[]> {
    return this.productionLineRepository.find({
      where: {
        type: type as 'fabric' | 'furniture' | 'metalworks' | 'shoes',
        status: 'active' as 'active',
      },
      relations: ['manager', 'machines'],
    });
  }
}
