import { CreateBusinessDto } from '@dtos/create-business.dto';
import {
  HttpException,
  HttpStatus,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Business, BusinessDocument } from '@schemas/business.schema';
import { Model } from 'mongoose';
import { CleanupService } from './cleanup.service';

@Injectable()
export class BusinessService {
  constructor(
    @InjectModel('business')
    private businessModel: Model<BusinessDocument>,
    private readonly cleanupSrv: CleanupService,
  ) {}

  async create(createEnterpriseDto: CreateBusinessDto) {
    const name = createEnterpriseDto.name;

    const exists = await this.businessModel.findOne({ name });
    if (exists) {
      throw new HttpException('El negocio ya existe', HttpStatus.CONFLICT);
    }
    const user = new this.businessModel(createEnterpriseDto);
    return await user.save();
  }

  async findAll(): Promise<Business[]> {
    const enterprises = await this.businessModel.find().exec();
    return enterprises;
  }

  async findOne(id: string): Promise<Business> {
    const enterprise = await this.businessModel.findById(id).exec();
    if (!enterprise) {
      throw new HttpException('El negocio no existe', HttpStatus.NOT_FOUND);
    }
    return enterprise;
  }

  async update(id: string, dto: CreateBusinessDto) {
    const shopping = await this.businessModel.findByIdAndUpdate(id, dto, {
      new: true,
    });
    if (!shopping) throw new NotFoundException('No encontrado');
    return shopping;
  }

  async remove(id: string) {
    await this.cleanupSrv.deleteBusinessData(id);
    await this.businessModel.findByIdAndDelete(id);
    return { message: 'Eliminado' };
  }
}
