import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Proposta } from './entities/proposta.entity';

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

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

  async selecionar(id: string) {
    const prop = await this.findOne(id);
    // Deselect others for same demanda
    await this.repo.update({ demanda_id: prop.demanda_id }, { selecionada: false });
    await this.repo.update(id, { selecionada: true, status: 'selecionada' });
    return this.findOne(id);
  }
}
