import { Injectable, Inject, NotFoundException, BadRequestException } from '@nestjs/common';
import { KYC_REPOSITORY, IKycRepository } from '../../domain/repositories/kyc.repository.interface';
import { USER_REPOSITORY, IUserRepository } from '../../domain/repositories/user.repository.interface';

@Injectable()
export class KycService {
  constructor(
    @Inject(KYC_REPOSITORY) private readonly kycRepo: IKycRepository,
    @Inject(USER_REPOSITORY) private readonly userRepo: IUserRepository,
  ) {}

  async submitKyc(userId: string, data: {
    targetLevel: number; fullName?: string; idType?: string; idNumber?: string;
    dateOfBirth?: string; idFrontUrl?: string; idBackUrl?: string; selfieUrl?: string;
    address?: string; annualIncome?: number; netWorth?: number;
  }) {
    const user = await this.userRepo.findById(userId);
    if (!user) throw new NotFoundException('User not found');

    if (data.targetLevel <= user.kycLevel) {
      throw new BadRequestException(`Already at KYC level ${user.kycLevel}`);
    }

    return this.kycRepo.create({
      userId,
      targetLevel: data.targetLevel,
      fullName: data.fullName || null,
      idType: data.idType || null,
      idNumber: data.idNumber || null,
      dateOfBirth: data.dateOfBirth ? new Date(data.dateOfBirth) : null,
      idFrontUrl: data.idFrontUrl || null,
      idBackUrl: data.idBackUrl || null,
      selfieUrl: data.selfieUrl || null,
      address: data.address || null,
      annualIncome: data.annualIncome || null,
      netWorth: data.netWorth || null,
      status: 'pending' as any,
    });
  }

  async getKycStatus(userId: string) {
    const submissions = await this.kycRepo.findByUserId(userId);
    const user = await this.userRepo.findById(userId);
    return {
      currentLevel: user?.kycLevel || 0,
      submissions: submissions.map(s => ({
        id: s.id, targetLevel: s.targetLevel, status: s.status,
        rejectReason: s.rejectReason, createdAt: s.createdAt,
      })),
    };
  }

  async reviewKyc(submissionId: string, approved: boolean, reviewedBy: string, rejectReason?: string) {
    const submission = await this.kycRepo.findById(submissionId);
    if (!submission) throw new NotFoundException('KYC submission not found');

    await this.kycRepo.updateStatus(
      submissionId,
      approved ? 'approved' : 'rejected',
      reviewedBy,
      rejectReason,
    );

    // If approved, update user's KYC level
    if (approved) {
      await this.userRepo.updateKycLevel(submission.userId, submission.targetLevel);
    }
  }

  async listPendingKyc(page: number, limit: number) {
    return this.kycRepo.findPending(page, limit);
  }
}
