import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import axios from 'axios';

@Injectable()
export class RecaptchaService {
    private readonly recaptchaSecretKey = process.env.RECAPTCHA_SECRET_KEY;

    async verifyRecaptcha(token: string)
    {
        try {
        const response = await axios.post(
            `https://www.google.com/recaptcha/api/siteverify`,
            null,
            {
                params: {
                    secret: this.recaptchaSecretKey,
                    response: token,
                },
            },
        );

        const { success, score } = response.data;

        // For v3, you may want to check the score
        if (!success || (score && score < 0.5)) {
            return false; // Invalid token or low score
        }

        return true; // Token is valid

        } catch (error) {
            throw new HttpException('Error validating reCAPTCHA', HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
