import { Injectable, UnauthorizedException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Company } from './company.entity';
import { IsNull } from 'typeorm';

@Injectable()
export class CompanyService {
  constructor(
    @InjectRepository(Company)
    private companyRepository: Repository<Company>,
  ) {}

  async findOne(where: any): Promise<Company | null> {
    return this.companyRepository.findOne({
      where: { ...where, deletedAt: IsNull() },
    });
  }

  async findAll(
    where: any = {},
    page: number = 1,
    limit: number = 10,
    orderBy: string = 'id',
    order: 'ASC' | 'DESC' = 'ASC',
  ): Promise<{ data: Company[]; total: number }> {
    const [data, total] = await this.companyRepository.findAndCount({
      where: { ...where, deletedAt: IsNull() },
      take: limit,
      skip: (page - 1) * limit,
      order: { [orderBy]: order },
    });

    return { data, total };
  }

  async upsert(empresaData: Partial<Company>): Promise<Company> {
    if (!empresaData.id) {
      // Create new Empresa
      const newEmpresa = this.companyRepository.create(empresaData);
      return this.companyRepository.save(newEmpresa);
    }

    // Update existing Empresa
    const existingEmpresa = await this.findOne({ id: empresaData.id });

    if (existingEmpresa) {
      this.companyRepository.merge(existingEmpresa, empresaData);
      return this.companyRepository.save(existingEmpresa);
    }

    throw new Error('Empresa não encontrada para atualização.');
  }

  async remove(id: number): Promise<void> {
    await this.companyRepository.softDelete(id);
  }

  async authenticate(cnpj: string, senha: string): Promise<Company> {
    const company = await this.companyRepository.findOne({ where: { cnpj, senha } });
    if (!company) {
      throw new UnauthorizedException('CNPJ ou senha inválidos');
    }
    return company;
  }
}