import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BaseRepository } from '@edr/api-common';
import { SavedSignature } from './entities/saved-signature.entity';

@Injectable()
export class SignaturesRepository extends BaseRepository<SavedSignature> {
  constructor(
    @InjectRepository(SavedSignature)
    repo: Repository<SavedSignature>,
  ) {
    super(repo);
  }

  findByUserId(userId: string): Promise<SavedSignature | null> {
    return this.repository.findOne({
      where: { userId } as never,
      relations: ['signatureFile'],
    });
  }

  /** Insert or update the single saved signature for a user. */
  async upsert(data: Partial<SavedSignature>): Promise<SavedSignature> {
    const existing = await this.repository.findOne({
      where: { userId: data.userId! } as never,
    });
    if (existing) {
      Object.assign(existing, data);
      return this.repository.save(existing);
    }
    return this.repository.save(this.repository.create(data));
  }
}
