import {CoreCatalogType, MediaCatalog, NavigationTypes, SiteCatalog, UserCatalog} from "./typings";
import CfExceptionHandler from "../../core/CfExceptionHandler";
import {checkObjectFieldEmptyiness, offsetToISO8601} from "../../utils";
import {injectCatalog} from "../../core/injector";

export async function validateAndSaveUserCatalog(userId: string, properties: UserCatalog) {

    if (userId == "") {
        new CfExceptionHandler().throwAndLogError(
            "user catalog",
            "invalid user id"
        );
        return;
    }
    const timezoneOffset = new Date().getTimezoneOffset();
    properties.timezone = offsetToISO8601(timezoneOffset);

    const bYear =
        properties.birth_year != undefined &&
        (properties.birth_year < 1900 ||
            properties.birth_year > new Date().getFullYear());
    if (bYear) {
        new CfExceptionHandler().throwAndLogError(
            "user catalog",
            "invalid user birth_year"
        );
        return;
    }
    injectCatalog(userId, CoreCatalogType.User, properties);
}

export async function validateAndSaveSiteCatalog(siteId: string, properties: SiteCatalog) {

    if (siteId == "") {
        new CfExceptionHandler().throwAndLogError(
            "site catalog",
            "invalid site id"
        );
        return;
    }

    checkObjectFieldEmptyiness(properties, ["country"]);
    injectCatalog(siteId, CoreCatalogType.Site, properties);
}

export async function validateAndSaveMediaCatalog(mediaId: string, properties: MediaCatalog) {

    if (mediaId == "") {
        new CfExceptionHandler().throwAndLogError(
            "media catalog",
            "invalid media item id"
        );
    } else if (properties.type == undefined) {
        new CfExceptionHandler().throwAndLogError(
            "media catalog",
            "invalid media type"
        );
    }

    checkObjectFieldEmptyiness(properties, ["type"]);
    injectCatalog(mediaId, CoreCatalogType.Media, properties);
}
