import { Repository } from 'typeorm';
import { AppDataSource } from '../index';
import { User } from '../entities/User.entity';

export class UserRepository {
  private repo: Repository<User>;

  constructor() {
    this.repo = AppDataSource.getRepository(User);
  }

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

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

  findByUsername(username: string): Promise<User | null> {
    return this.repo.findOne({ where: { username } });
  }

  findByOAuth(
    provider: 'google' | 'linkedin',
    subject: string,
  ): Promise<User | null> {
    return this.repo.findOne({
      where: { authProvider: provider, oauthSubject: subject },
    });
  }

  create(data: Partial<User>): Promise<User> {
    const user = this.repo.create(data);
    return this.repo.save(user);
  }

  async deleteById(id: string): Promise<void> {
    await this.repo.delete(id);
  }

  async update(id: string, data: Partial<User>): Promise<User> {
    await this.repo.update(id, data);
    const user = await this.findById(id);
    if (!user) throw new Error('User not found');
    return user;
  }
}
