import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { Sequelize } from 'sequelize-typescript';
import * as bcrypt from 'bcrypt';
import { UnidSaude } from 'src/unid-saude/entity/unid-saude.model';
import { CreateUnidSaudeParams } from 'src/utils/types';

@Injectable()
export class UnidSaudeService {
  constructor(
    private sequelize: Sequelize,
    @InjectModel(UnidSaude)
    private unidSaudeModel: typeof UnidSaude,) {}

    async findAllUnid(): Promise<UnidSaude[]> {
      return this.unidSaudeModel.findAll();
    }
  
    findOneUnid(id: number): Promise<UnidSaude> {
      return this.unidSaudeModel.findOne({
        where: {
          id,
        },
      });
    }

    async createUnid(unidSaudeDetails: CreateUnidSaudeParams): Promise<UnidSaude> {
      const createUnidSaude = await this.unidSaudeModel.create({
        ...unidSaudeDetails,
        senha: await bcrypt.hash(unidSaudeDetails.senha, 10),
      });
      return {
        ...createUnidSaude.get(),
        senha: undefined,
      }; 
    }

  async updateUnid(id: number, unidadeSaude: UnidSaude): Promise<[string, UnidSaude[]]> {
    const [affectedCount, updatedUnidadesSaude] = await this.unidSaudeModel.update(unidadeSaude, { where: { id }, returning: true });
  
    if (affectedCount > 0) {
      return ['success', updatedUnidadesSaude];
    }
  }


  async removeUnid(id: number): Promise<void> {
    const unidSaude = await this.unidSaudeModel.findByPk(id);

    if (unidSaude) {
      await unidSaude.destroy();
    }
  }

    }