import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { CreateColonneDto } from './dto/create-colonne.dto';
import { UpdateColonneDto } from './dto/update-colonne.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Colonne } from './entities/colonne.entity';
import { Repository } from 'typeorm';

@Injectable()
export class ColonnesService {
  constructor(
        @InjectRepository(Colonne)
        private colonneRepository: Repository<Colonne>
      ) { }
    
      async create(createColonneDto: CreateColonneDto) {
    
         // Forcer le libellé en minuscules
        createColonneDto.libelle = createColonneDto.libelle.toLowerCase().trim();

        const existing = await this.colonneRepository.findOne({where: {libelle: createColonneDto.libelle}});
        // 2. Si existe → retourner une erreur
        if (existing) {
          throw new ConflictException('Cette colonne existe déjà');
        }
        

        return await this.colonneRepository.save(createColonneDto);
    
    
      }
    
      async findAll() {
        const agence = await this.colonneRepository.find();
        //return banques.map(({ id, ...data }) => data); // retire l'id
        return agence;
      }
    
      async findOne(id: number) {
          const checkTypeDoc = await this.colonneRepository.findBy({id});
          return checkTypeDoc;
        }
      
        async update(id: number, updateColonneDto: UpdateColonneDto) {
          // Forcer le libellé en minuscules
          updateColonneDto.libelle = updateColonneDto.libelle.toLowerCase().trim();
          const checkBanque = await this.colonneRepository.preload({id, ...updateColonneDto});
          if (!checkBanque) {
            throw new NotFoundException('Aucune valeur trouvée');
          }
          
          return this.colonneRepository.save(checkBanque);
        }
    
      remove(id: number) {
        return `This action removes a #${id} agence`;
      }
}
