import { DSQL_MYSQL_user_databases_Type } from "../../../../types";
import grabDbFullName from "../../../../utils/grab-db-full-name";
import varDatabaseDbHandler from "../../../backend/varDatabaseDbHandler";

type Return = {
    success: boolean;
    msg?: string;
    error?: string;
};

type Param = {
    key?: string;
    database: string;
    email: string;
    encryptionKey?: string;
    encryptionSalt?: string;
    debug?: boolean;
    apiUserID?: string | number;
    dbUserId?: string | number;
};

/**
 * # API Login
 */
export default async function apiSendResetPasswordLink({
    database,
    email,
    dbUserId,
    debug,
}: Param): Promise<Return> {
    const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });

    /**
     * Check input validity
     *
     * @description Check input validity
     */
    if (email?.match(/ /)) {
        return {
            success: false,
            msg: "Invalid Email/Password format",
        };
    }

    let foundUser = await varDatabaseDbHandler({
        queryString: `SELECT * FROM ${dbFullName}.users WHERE email = ? OR username = ?`,
        queryValuesArray: [email, email],
        database: dbFullName,
        debug,
    });

    if (debug) {
        console.log("apiSendResetPassword:foundUser:", foundUser);
    }

    const targetUser = foundUser?.[0] as
        | DSQL_MYSQL_user_databases_Type
        | undefined;

    if (!targetUser)
        return {
            success: false,
            msg: "No user found",
        };

    return { success: true };
}

export type SendResetPasswordParam = Param;
export type SendResetPasswordReturn = Return;
