const {onRequest} = require("firebase-functions/v2/https");
const {getAuth} = require("firebase-admin/auth");
const {getFirestore} = require("firebase-admin/firestore");
const admin = require("firebase-admin");
const logger = require("firebase-functions/logger");

admin.initializeApp();

exports.createSubUser = onRequest(async (request, response) => {
    try {
        logger.info("Processing user creation", {requestBody: request.body.data});

        const {userType, name, email, password} = request.body.data;

        if (!email || !password || !name || !userType) {
            throw new Error("Missing required fields");
        }

        const userRecord = await getAuth().createUser({
            email,
            password,
            displayName: name,
        });

        const userProfile = {
            userType,
            name,
            email,
            uid: userRecord.uid,
        };

        await getFirestore().collection("Profiles").doc(userRecord.uid).set(userProfile);

        response.status(200).json({
            data: {

                message: "User created successfully",
                userId: userRecord.uid,
            }
        });
    } catch (error) {
        logger.error("Error in createSubUser function", {error: error.message});
        response.status(500).json({data: {error: error.message}});
    }
});
