import Joi from 'joi';
import bcrypt from 'bcrypt';
import asyncHandler from '#middlewares/asyncHandler';
import Wallet from '#models/userWallet';

// Validation function for signup data
const validateSignup = (req: any) => {
    const schema = Joi.object({
        email: Joi.string().required().email(),
        password: Joi.string().min(8).max(255).required(),
    });

    return schema.validate(req);
};

// Validation function for login data
const validateLogin = (req: any) => {
    const schema = Joi.object({
        email: Joi.string().required().email(),
        password: Joi.string().min(8).max(255).required(),
    });

    return schema.validate(req);
};

/**
 @desc     Wallet Signup
 @route    POST /api/auth/signup
 @access   Public
 */
const signupWallet = asyncHandler(async (req: any, res: any): Promise<any> => {
    console.log("Signup attempt:", req.body);

    // Validate the request body
    const { error } = validateSignup(req.body);
    if (error) {
        return res.status(400).send({ status: false, message: error.details[0].message });
    }

    // Check if the email is already registered
    let wallet = await Wallet.findOne({ email: req.body.email });
    if (wallet) {
        return res.status(400).send("Email already registered.");
    }

    // Hash the password before saving it
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(req.body.password, salt);

    // Create a new wallet instance
    wallet = new Wallet({
        email: req.body.email,
        password: hashedPassword,
    });

    // Save the new wallet to the database
    await wallet.save();

    // Generate a JWT token for the new wallet
    const token = wallet.generateAuthToken();

    // Send back the response with the token and wallet info
    return res
        .cookie("x-auth-token", token, {
            httpOnly: true,
            maxAge: 5 * 24 * 60 * 60 * 1000, // 1 year
            secure: process.env.NODE_ENV === 'production', // Use secure cookies in production
        })
        .header("x-auth-token", token)
        .header("access-control-expose-headers", "x-auth-token")
        .status(201)
        .send({
            status: true,
            message: "Wallet created successfully",
            wallet: wallet,  // Return wallet details (you can adjust as needed)
        });
});



    /**
     @desc     Wallet Login
    @route    POST /api/auth
    @access   Public
    */
    const loginWallet = asyncHandler(async (req: any, res: any): Promise<any> => {
        console.log("Login attempt:", req.body);

        // Validate request body
        const { error } = validateLogin(req.body);
        if (error) {
            return res.status(400).send({ status: false, message: error.details[0].message });
        }

        // Find wallet by email
        let wallet = await Wallet.findOne({ email: req.body.email });
        if (!wallet) {
            return res.status(400).send("Invalid email or password.");
        }

        // Compare the provided password with the stored password hash
        const validPassword = await bcrypt.compare(req.body.password, wallet.password);
        if (!validPassword) {
            return res.status(400).send("Invalid email or password.");
        }

        // Generate an auth token
        const token = wallet.generateAuthToken();

            // Send back the response with token and user info
            return res
                .cookie("x-auth-token", token, {
                    httpOnly: true,
                    maxAge: 365 * 24 * 60 * 60 * 1000, // 1 year
                    secure: process.env.NODE_ENV === 'production', // Use secure cookies in production
                })
                .header("x-auth-token", token)
                .header("access-control-expose-headers", "x-auth-token")
                .status(200)
                .send({
                    status: true,
                    message: "Wallet login successful",
                    wallet: wallet, // Send wallet details (you can modify as needed)
                });
        });

/**
 @desc     Clear Cookies (Logout)
 @route    GET /api/auth/logout
 @access   Public
 */
const logoutWallet = asyncHandler(async (req: any, res: any): Promise<any> => {
    res.clearCookie("x-auth-token"); // Clear the x-auth-token cookie
    res.status(200).send({ status: true, message: "Successfully logged out" });
});


export { loginWallet, logoutWallet, signupWallet };
