const express = require("express");
const firebase = require("firebase-admin");
const { body, validationResult } = require('express-validator');
const cors = require("cors");
const router = express.Router();
const forgotPasswordController = require('../controllers/forgotpassword.controller');


router.post("/send",     
        body('email').isEmail().withMessage('email field must be a valid email'),
        async (req, res, next) => {

        const email = req.body.email;
        console.log(email);

        const errors = validationResult(req);

        if(!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        try {
            const resetLink = await firebase.auth().generatePasswordResetLink(email);
            await forgotPasswordController.sendResetLink(email, resetLink);
            return res.status(200).send();
    
        } catch (error) {
            console.log(error);
            return res.status(500).send({error: error.errorInfo.message});
        }
  });
  
module.exports = router;