import { InjectRepository } from '@nestjs/typeorm';
import { Category } from './entities/category.entity';
import { ILike, Like, Not, Repository } from 'typeorm';
import { getCompleteUrl } from 'src/common/helper';

export class CategoryRepository {
  @InjectRepository(Category)
  private readonly categoryRepository: Repository<Category>;

  async findAllCategory(
    take: number,
    skip: number,
    search: string,
    headers: any,
    isActive: any,
  ) {
    const conditions: any = {
      ...(isActive ? { status: 1 } : {}),
      ...(headers && headers['device-type'] === 'mobile' ? { status: 1 } : {}),
      ...(search ? { name: ILike(`%${search}%`) } : {}),
    };

    const [data, count] = await this.categoryRepository.findAndCount({
      where: conditions,
      skip,
      take,
      select: ['id', 'name', 'status', 'media'],
      order: { created_at: 'DESC' },
    });

    const result = data.map((data) => ({
      ...data,
      media: getCompleteUrl(data.media),
    }));

    const response = {
      count,
      data: result,
    };

    return response;
  }

  async findById(id: string) {
    const data = await this.categoryRepository.findOne({
      where: {
        id: id,
      },
      select: ['id', 'name', 'status', 'media'],
    });

    if (data) {
      const completeUrl = getCompleteUrl(data.media);
      const response = {
        ...data,
        media: completeUrl,
      };
      return response;
    }
  }

  async isUnique(name: string, id?: string) {
    const whereCondition: any = { name: ILike(name) };
    if (id) {
      whereCondition.id = Not(id);
    }

    const data = await this.categoryRepository.find({
      where: whereCondition,
    });

    return data.length > 0;
  }
}
