import { BadRequestException, Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";

import { User } from "@tria-plc/iamapi-common/entities/iam/user/user.entity";

export interface CheckAvailabilityQuery {
  email?: string;
  phone?: string;
}

export interface CheckAvailabilityResult {
  emailTaken: boolean;
  phoneTaken: boolean;
}

@Injectable()
export class CheckAvailabilityService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  async check({
    email,
    phone,
  }: CheckAvailabilityQuery): Promise<CheckAvailabilityResult> {
    if (!email && !phone) {
      throw new BadRequestException("email or phone is required");
    }

    const matches = await this.userRepository.find({
      where: [
        ...(email ? [{ email }] : []),
        ...(phone ? [{ phoneNumber: phone }] : []),
      ],
      select: { id: true, email: true, phoneNumber: true },
    });

    return {
      emailTaken: email ? matches.some((user) => user.email === email) : false,
      phoneTaken: phone
        ? matches.some((user) => user.phoneNumber === phone)
        : false,
    };
  }
}
