import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { KycSubmission } from '../../domain/entities/kyc-submission.entity';
import { IKycRepository } from '../../domain/repositories/kyc.repository.interface';

@Injectable()
export class KycRepository implements IKycRepository {
  constructor(@InjectRepository(KycSubmission) private readonly repo: Repository<KycSubmission>) {}

  async create(data: Partial<KycSubmission>): Promise<KycSubmission> {
    const submission = this.repo.create(data);
    return this.repo.save(submission);
  }

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

  async findByUserId(userId: string): Promise<KycSubmission[]> {
    return this.repo.find({ where: { userId }, order: { createdAt: 'DESC' } });
  }

  async findLatestByUserId(userId: string): Promise<KycSubmission | null> {
    return this.repo.findOne({ where: { userId }, order: { createdAt: 'DESC' } });
  }

  async findPending(page: number, limit: number): Promise<[KycSubmission[], number]> {
    return this.repo.findAndCount({
      where: { status: 'pending' as any },
      skip: (page - 1) * limit,
      take: limit,
      order: { createdAt: 'ASC' },
      relations: ['user'],
    });
  }

  async updateStatus(id: string, status: string, reviewedBy: string, rejectReason?: string): Promise<void> {
    await this.repo.update(id, {
      status: status as any,
      reviewedBy,
      reviewedAt: new Date(),
      rejectReason: rejectReason || null,
    });
  }

  async save(submission: KycSubmission): Promise<KycSubmission> {
    return this.repo.save(submission);
  }
}
