import { Brackets, Equal, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { getCompleteUrl, isEmpty } from 'src/common/helper';
import { Offer } from './entities/offer.entity';
import * as moment from 'moment';

export class OffersRepository {
  constructor(
    @InjectRepository(Offer)
    private readonly offersRepository: Repository<Offer>,
  ) {}

  async findAll(take: number, skip: number, search: string, headers: any) {
    let offersObj = this.offersRepository.createQueryBuilder('offer');

    const currentDate = moment().format('YYYY-MM-DD');

    if (headers && headers['device-type'] === 'mobile') {
      offersObj = offersObj
        .andWhere('DATE(offer.end_date) > :currentDate', { currentDate })
        .andWhere('offer.status = :status', { status: 1 });
    }

    if (search) {
      offersObj = offersObj.andWhere(
        new Brackets((qb) => {
          qb.where('offer.title ILIKE :search', {
            search: `%${search}%`,
          }).orWhere('offer.description ILIKE :search', {
            search: `%${search}%`,
          });
        }),
      );
    }

    const [result, count] = await offersObj
      .orderBy('offer.created_at', 'DESC')
      .skip(skip)
      .take(take)
      .getManyAndCount();

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

    const response = {
      count,
      data,
    };

    return response;
  }

  async findOne(id: string) {
    const data = await this.offersRepository.findOne({
      where: {
        id,
      },
    });

    return data;
  }

  async findOfferDetails(id: string) {
    const data = await this.offersRepository.findOne({
      where: {
        id,
      },
    });

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

      return response;
    }
  }
}
