import { Headers, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { PostEntity } from './entities/post.entity';

@Injectable()
export class PostRepository {
  constructor(
    @InjectRepository(PostEntity)
    private readonly postRepository: Repository<PostEntity>,
  ) {}

  async findAll(take: number, skip: number, filterParams?: any, headers?: any) {
    let queryBuilder = this.postRepository
      .createQueryBuilder('post')
      .orderBy('post.created_at', 'DESC')
      .skip(skip)
      .take(take)
      .innerJoinAndSelect('post.user', 'user');

    if (headers && headers['device-type'] === 'mobile') {
      queryBuilder = queryBuilder.andWhere('post.status = :status', {
        status: 1,
      });

      if (filterParams.search) {
        queryBuilder = queryBuilder.andWhere('post.title ILIKE :search', {
          search: `%${filterParams.search}%`,
        });
      }
    } else {
      queryBuilder = queryBuilder.andWhere('post.status IN (:...statuses)', {
        statuses: [0, 1],
      });

      if (filterParams) {
        const { search, startDate, endDate } = filterParams;

        if (search) {
          queryBuilder = queryBuilder.where(
            '(user.first_name ILIKE :search OR post.title ILIKE :search OR post.description ILIKE :search)',
            { search: `%${search}%` },
          );
        }

        if (startDate) {
          if (endDate && startDate === endDate) {
            queryBuilder = queryBuilder.andWhere(
              'DATE(post.created_at) = :startDate',
              {
                startDate,
              },
            );
          } else {
            queryBuilder = queryBuilder.andWhere(
              'DATE(post.created_at) >= :startDate',
              {
                startDate,
              },
            );
          }
        }

        if (endDate && startDate !== endDate) {
          queryBuilder = queryBuilder.andWhere(
            'DATE(post.created_at) <= :endDate',
            {
              endDate,
            },
          );
        }
      }
    }

    const [data, count] = await queryBuilder.getManyAndCount();

    data.forEach((post) => {
      if (post.user.profile_picture) {
        post.user.profile_picture = `${process.env.DOMAIN}${post.user.profile_picture}`;
      }
    });

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

    return response;
  }

  async findAllReportedPOST(take: number, skip: number, filterParams?: any) {
    let queryBuilder = this.postRepository
      .createQueryBuilder('post')
      .withDeleted()
      .orderBy('post.created_at', 'DESC')
      .skip(skip)
      .take(take)
      .innerJoinAndSelect('post.user', 'user')
      .where('post.status = :status', { status: 2 });

    if (filterParams) {
      const { search, startDate, endDate } = filterParams;
      if (search) {
        queryBuilder = queryBuilder.andWhere(
          '(user.first_name ILIKE :search OR post.title ILIKE :search OR post.description ILIKE :search)',
          { search: `%${search}%` },
        );
      }

      if (startDate) {
        if (endDate && startDate === endDate) {
          queryBuilder = queryBuilder.andWhere(
            'DATE(post.created_at) = :startDate',
            {
              startDate,
            },
          );
        } else {
          queryBuilder = queryBuilder.andWhere(
            'DATE(post.created_at) >= :startDate',
            {
              startDate,
            },
          );
        }
      }

      if (endDate && startDate !== endDate) {
        queryBuilder = queryBuilder.andWhere(
          'DATE(post.created_at) <= :endDate',
          {
            endDate,
          },
        );
      }
    }

    const [data, count] = await queryBuilder.getManyAndCount();

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

    return response;
  }

  async findOne(id: string) {
    return this.postRepository.findOne({ where: { id } });
  }
}
