import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../../domain/entities/user.entity';

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

  async findByEmail(email: string): Promise<User | null> {
    return this.repo.findOneBy({ email });
  }

  async findByPhone(phone: string): Promise<User | null> {
    return this.repo.findOneBy({ phone });
  }

  /** Find by email or phone (for login with either identifier) */
  async findByIdentifier(identifier: string): Promise<User | null> {
    const isPhone = /^[+\d][\d\s\-().]{6,}$/.test(identifier);
    if (isPhone) {
      const byPhone = await this.findByPhone(identifier);
      if (byPhone) return byPhone;
    }
    return this.findByEmail(identifier);
  }

  async findById(id: string): Promise<User | null> {
    return this.repo.findOneBy({ id });
  }

  async save(user: User): Promise<User> {
    return this.repo.save(user);
  }
}
