import {
  BadRequestException,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { CreateCategoryDto } from './dto/create-category.dto';
import { UpdateCategoryDto } from './dto/update-category.dto';
import isValidUuidV4 from 'src/common/uuid validator/uuid-validate';
import { isEmpty } from 'class-validator';
import { lan } from 'src/lan';
import { Category } from './entities/category.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CategoryRepository } from './categories.repository';

@Injectable()
export class CategoriesService {
  constructor(
    @InjectRepository(Category)
    private readonly categoryEntity: Repository<Category>,
    private readonly categoryRepository: CategoryRepository,
  ) {}

  async create(createCategoryDto: CreateCategoryDto) {
    if (await this.categoryRepository.isUnique(createCategoryDto.name)) {
      throw new BadRequestException(lan('data_already_exists'));
    }

    const category = new Category();

    Object.assign(category, createCategoryDto);
    const data = await this.categoryEntity.save(category);

    return data;
  }

  async findAll(
    take: number,
    skip: number,
    search: string,
    headers: any,
    isActive: any,
  ) {
    return this.categoryRepository.findAllCategory(
      take,
      skip,
      search,
      headers,
      isActive,
    );
  }

  async findOne(id: string) {
    if (!isValidUuidV4(id)) {
      throw new BadRequestException(lan('common.invalid_uuid_format'));
    }

    const data = await this.categoryRepository.findById(id);

    if (isEmpty(data)) {
      throw new NotFoundException(lan('common.data_not_found'));
    }

    return data;
  }

  async update(id: string, updateCategoryDto: UpdateCategoryDto) {
    if (await this.categoryRepository.isUnique(updateCategoryDto.name, id)) {
      throw new BadRequestException(lan('data_already_exists'));
    }

    const data = await this.categoryRepository.findById(id);

    if (isEmpty(data)) {
      throw new NotFoundException(lan('common.data_not_found'));
    }

    const category = new Category();
    Object.assign(category, updateCategoryDto);

    const updatedCategory = await this.categoryEntity.update(id, category);

    return updatedCategory;
  }

  async remove(id: string) {
    if (!isValidUuidV4(id)) {
      throw new BadRequestException(lan('common.invalid_uuid_format'));
    }

    const province = await this.categoryRepository.findById(id);

    if (isEmpty(province)) {
      throw new NotFoundException(lan('common.data_not_found'));
    }

    await this.categoryEntity.delete(id);
  }
}
