import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common';
import * as bcrypt from 'bcryptjs';
import { randomInt } from 'node:crypto';
import { PrismaService } from '../infra/prisma.service';
import { SettingsService } from './settings.service';

@Injectable()
export class OtpService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly settings: SettingsService
  ) {}

  async send(command: { target: string; channel: string; purpose: string; userId?: string }) {
    const expiryMinutes = await this.settings.getNumber('OTP_EXPIRY_MINUTES', 10);
    const code = String(randomInt(100000, 999999));
    const expiresAt = new Date(Date.now() + expiryMinutes * 60_000);
    await this.prisma.authCode.create({
      data: {
        userId: command.userId,
        target: command.target,
        channel: command.channel,
        purpose: command.purpose,
        codeHash: await bcrypt.hash(code, 10),
        expiresAt
      }
    });
    console.log(`OTP ${command.channel} для ${command.target}: ${code}`);
    return { sent: true, expiresAt: expiresAt.toISOString() };
  }

  async verify(command: { target: string; code: string; purpose: string }) {
    const authCode = await this.prisma.authCode.findFirst({
      where: {
        target: command.target,
        purpose: command.purpose,
        usedAt: null,
        expiresAt: { gt: new Date() }
      },
      orderBy: { createdAt: 'desc' }
    });

    if (!authCode) throw new BadRequestException('Код подтверждения не найден или истек');
    const matches = await bcrypt.compare(command.code, authCode.codeHash);
    if (!matches) throw new UnauthorizedException('Неверный код подтверждения');
    await this.prisma.authCode.update({ where: { id: authCode.id }, data: { usedAt: new Date() } });
    return { verified: true };
  }
}
