import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Demanda } from './entities/demanda.entity';
import { ItemLinha } from './entities/item-linha.entity';

@Injectable()
export class DemandasService {
  constructor(
    @InjectRepository(Demanda) private repo: Repository<Demanda>,
    @InjectRepository(ItemLinha) private itemRepo: Repository<ItemLinha>,
  ) {}

  findAll(query?: any) {
    const where: any = {};
    if (query?.status) where.status = query.status;
    if (query?.centro_custo_id) where.centro_custo_id = query.centro_custo_id;
    if (query?.categoria_id) where.categoria_id = query.categoria_id;
    return this.repo.find({ where, relations: ['itens_linha'], order: { created_at: 'DESC' } });
  }

  findOne(id: string) { return this.repo.findOne({ where: { id }, relations: ['itens_linha'] }); }
  create(data: Partial<Demanda>) { return this.repo.save(data); }
  async update(id: string, data: Partial<Demanda>) { await this.repo.update(id, data); return this.findOne(id); }
  async remove(id: string) { await this.repo.delete(id); return { deleted: true }; }

  async updateStatus(id: string, status: string) {
    await this.repo.update(id, { status });
    return this.findOne(id);
  }

  findItens(demandaId: string) { return this.itemRepo.find({ where: { demanda_id: demandaId }, order: { ordem: 'ASC' } }); }
  createItem(data: Partial<ItemLinha>) { return this.itemRepo.save(data); }
  async updateItem(id: string, data: Partial<ItemLinha>) { await this.itemRepo.update(id, data); return this.itemRepo.findOne({ where: { id } }); }
  async removeItem(id: string) { await this.itemRepo.delete(id); }
}
