import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { UserEntity } from './entities/user.entity';
import { Repository } from 'typeorm';
import { getCompleteUrl, isEmpty } from 'src/common/helper';
import { AppUser } from 'src/app_users/entities/app_user.entity';

@Injectable()
export class UserRepository {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
    @InjectRepository(AppUser)
    private readonly appUserRepository: Repository<AppUser>,
  ) {}

  async findAll() {
    const data = await this.userRepository.find();

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

    return completeUrl;
  }

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

    if (data) {
      const completeUrl = getCompleteUrl(data.profile_picture);

      const response = {
        ...data,
        profile_picture: completeUrl,
      };

      return response;
    }
  }

  async findUserId(id: string) {
    const data = await this.userRepository.findOne({ where: { id } });
    if (data) {
      const response = {
        ...data,
      };

      return response;
    }
  }

  async findOneForPassword(email: string) {
    const data = await this.userRepository.findOne({ where: { email } });

    if (data) {
      const response = {
        ...data,
      };

      return response;
    }
  }

  async findByEmail(email: string) {
    const data = await this.userRepository.findOne({ where: { email } });

    if (data) {
      const completeUrl = getCompleteUrl(data.profile_picture);

      const response = {
        ...data,
        profile_picture: completeUrl,
      };

      return response;
    }
  }

  async findUserTokenExpiry(access_token: string) {
    const actualToken = access_token.replace(/^Bearer\s/, '');

    const user = await this.userRepository.findOne({
      where: { access_token: actualToken },
    });

    return user;
  }

  async findAppUserTokenExpiry(access_token: string) {
    const actualToken = access_token.replace(/^Bearer\s/, '');

    const user = await this.appUserRepository.findOne({
      where: { access_token: actualToken },
    });

    return user;
  }
}
