import { ForbiddenException, Injectable } from '@nestjs/common';
import * as crypto from 'crypto';
import { PrismaService } from '../prisma/prisma.service';
import { ProgressService } from '../progress/progress.service';

@Injectable()
export class CertificateService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly progress: ProgressService,
  ) {}

  /**
   * Returns certificate data ONLY if the server confirms eligibility.
   * Mirrors raseedna_get_certificate_data(): an ineligible user's response
   * never includes certificate data at all — nothing to reveal client-side.
   */
  async getCertificate(userId: string) {
    const eligible = await this.progress.isCertificateEligible(userId);
    if (!eligible) {
      throw new ForbiddenException('لم يكمل الطفل جميع الفصول بعد — الشهادة غير متاحة حتى الآن.');
    }

    let cert = await this.prisma.certificate.findFirst({ where: { userId } });
    if (!cert) {
      const user = await this.prisma.user.findUniqueOrThrow({ where: { id: userId } });
      cert = await this.prisma.certificate.create({
        data: {
          userId,
          certificateNumber: `RSDN-${crypto.randomBytes(6).toString('hex').toUpperCase()}`,
        },
      });
      // Parent notification (opt-in only) would be dispatched here via a
      // mail provider — left as an integration point (see docs/DEPLOYMENT.md).
      void user;
    }

    const user = await this.prisma.user.findUniqueOrThrow({ where: { id: userId } });
    return {
      childName: user.displayName,
      certificateNumber: cert.certificateNumber,
      issuedAt: cert.issuedAt,
      fileUrl: cert.fileUrl,
    };
  }
}
