import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { CreateTypedocumentDto } from './dto/create-typedocument.dto';
import { UpdateTypedocumentDto } from './dto/update-typedocument.dto';
import { Typedocument } from './entities/typedocument.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class TypedocumentService {
  
  constructor(
      @InjectRepository(Typedocument)
      private typeDocRepository: Repository<Typedocument>
    ) { }
  
    async create(createTypedocumentDto: CreateTypedocumentDto) {
  
      const existing = await this.typeDocRepository.findOne({where: {libelle: createTypedocumentDto.libelle}});
      // 2. Si existe → retourner une erreur
      if (existing) {
        throw new ConflictException('Ce type de document existe déjà');
      }
  
      return await this.typeDocRepository.save(createTypedocumentDto);
  
  
    }
  
    async findAll() {
      const agence = await this.typeDocRepository.find();
      //return banques.map(({ id, ...data }) => data); // retire l'id
      return agence;
    }
  
    async findOne(id: number) {
        const checkTypeDoc = await this.typeDocRepository.findBy({id});
        return checkTypeDoc;
      }
    
      async update(id: number, updateTypedocumentDto: UpdateTypedocumentDto) {
        const checkBanque = await this.typeDocRepository.preload({id, ...updateTypedocumentDto});
        if (!checkBanque) {
          throw new NotFoundException('Aucune valeur trouvée');
        }
        // const existing = await this.typeDocRepository.findOne({where: {codeagence: updateBanqueDto.codeagence}});
        // // 2. Si existe → retourner une erreur
        // if (existing) {
        //   throw new ConflictException('Ce code agence existe déjà');
        // }
        
        return this.typeDocRepository.save(checkBanque);
      }
  
    remove(id: number) {
      return `This action removes a #${id} agence`;
    }

}
