import fs from "fs";
import path from "path";

export default function getServiceImage(
    serviceId: string,
    image: string | null | undefined,
    fallback: string
): string {
    const rootPath = process.env.PUBLIC_SERVICE_IMAGE_URL;
    if (serviceId == null) return fallback;
    if (image == undefined || image == null || image === "") return fallback;

    const rootDir =
        process.env.NODE_ENV !== "production"
            ? process.env.GET_SERVICE_IMAGE_FILES_ROOT_DEV
            : process.env.GET_SERVICE_IMAGE_FILES_ROOT_PRO;

    const uploadPath = path.join(__dirname, rootDir + serviceId);

    const filePath = path.join(uploadPath, image);

    if (!fs.existsSync(filePath)) {
        return fallback;
    }

    return image ? rootPath + serviceId + "/" + image : "";
}
