import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { WorkflowAprovacao } from './entities/workflow-aprovacao.entity';

@Injectable()
export class WorkflowService {
  constructor(@InjectRepository(WorkflowAprovacao) private repo: Repository<WorkflowAprovacao>) {}

  findAll() { return this.repo.find(); }
  findOne(id: string) { return this.repo.findOne({ where: { id } }); }
  findByDemanda(demandaId: string) { return this.repo.findOne({ where: { demanda_id: demandaId } }); }
  create(data: Partial<WorkflowAprovacao>) { return this.repo.save(data); }

  async aprovar(id: string, observacao?: string) {
    const wf = await this.repo.findOneOrFail({ where: { id } });
    const etapas = wf.etapas as any[];
    const current = etapas[wf.etapa_atual - 1];
    if (current) {
      current.status = 'aprovado';
      current.data_acao = new Date().toISOString();
      current.observacao = observacao || 'Aprovado';
    }
    if (wf.etapa_atual >= etapas.length) {
      wf.status = 'aprovado';
    } else {
      wf.etapa_atual++;
      wf.status = 'em_andamento';
    }
    wf.etapas = etapas;
    return this.repo.save(wf);
  }

  async reprovar(id: string, observacao: string) {
    const wf = await this.repo.findOneOrFail({ where: { id } });
    const etapas = wf.etapas as any[];
    const current = etapas[wf.etapa_atual - 1];
    if (current) {
      current.status = 'reprovado';
      current.data_acao = new Date().toISOString();
      current.observacao = observacao;
    }
    wf.status = 'reprovado';
    wf.etapas = etapas;
    return this.repo.save(wf);
  }

  findPendentes() {
    return this.repo.find({ where: { status: 'pendente' } });
  }
}
