import { CreateTaxDto } from '@dtos/create-tax-dto';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Taxes, TaxesDocument } from '@schemas/taxes.schema';
import { UserDocument } from '@schemas/user.schema';
import { Model } from 'mongoose';

@Injectable()
export class TaxesService {
  constructor(
    @InjectModel('taxes')
    private readonly taxModel: Model<TaxesDocument>,
    @InjectModel('users') private userModel: Model<UserDocument>,
  ) {}

  async findAll(userId: string): Promise<Taxes[]> {
    const user = await this.userModel.findById(userId).exec();
    if (!user) {
      throw new HttpException('Datos incorrectos', HttpStatus.NOT_FOUND);
    }

    return await this.taxModel.find({ businessId: user.businessId }).exec();
  }

  async update(dto: CreateTaxDto, userId: string): Promise<Taxes> {
    if (dto._id) {
      const doc = await this.taxModel.findByIdAndUpdate(dto._id, dto, {
        new: true,
      });

      if (!doc)
        throw new HttpException('Item no encontrado', HttpStatus.NOT_FOUND);
      return doc;
    } else {
      const user = await this.userModel.findById(userId).exec();
      if (!user) {
        throw new HttpException('Datos incorrectos', HttpStatus.NOT_FOUND);
      }
      return this.taxModel.create({
        businessId: user.businessId,
        ...dto,
      });
    }
  }
}
