import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SocialAccount, SocialProvider } from '../../domain/entities/social-account.entity';
import { ISocialAccountRepository } from '../../domain/repositories/social-account.repository.interface';

@Injectable()
export class SocialAccountRepository implements ISocialAccountRepository {
  constructor(
    @InjectRepository(SocialAccount)
    private readonly repo: Repository<SocialAccount>,
  ) {}

  async findByProviderAndOpenid(
    provider: SocialProvider,
    openid: string,
  ): Promise<SocialAccount | null> {
    return this.repo.findOne({ where: { provider, openid } });
  }

  async findByProviderAndUnionid(
    provider: SocialProvider,
    unionid: string,
  ): Promise<SocialAccount | null> {
    return this.repo.findOne({ where: { provider, unionid } });
  }

  async findByUserAndProvider(
    userId: string,
    provider: SocialProvider,
  ): Promise<SocialAccount | null> {
    return this.repo.findOne({ where: { userId, provider } });
  }

  async create(data: {
    userId: string;
    provider: SocialProvider;
    openid: string;
    unionid?: string;
    nickname?: string;
    avatarUrl?: string;
    rawData?: Record<string, unknown>;
  }): Promise<SocialAccount> {
    const entity = this.repo.create({
      userId: data.userId,
      provider: data.provider,
      openid: data.openid,
      unionid: data.unionid ?? null,
      nickname: data.nickname ?? null,
      avatarUrl: data.avatarUrl ?? null,
      rawData: data.rawData ?? null,
    });
    return this.repo.save(entity);
  }

  async save(account: SocialAccount): Promise<SocialAccount> {
    return this.repo.save(account);
  }

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