'use strict';

var tslib_es6 = require('./tslib.es6-2c2ed574.js');
var constantsIsProduction = require('./constantsIsProduction.js');
var normalizeLink = require('./normalizeLink-20e290e8.js');
var index = require('./index-6ce6e395.js');
var miscCookieHelper = require('./miscCookieHelper.js');
var Locale = require('./Locale-fbe01177.js');
var constantsDomainLocales = require('./constantsDomainLocales.js');

const SSO_V2_PATHS = {
    LOGIN_BY_SOCIAL: 'member/social-login',
    EMAIL: {
        REGISTER_BY_SEND_OTP: 'login/login-with-email',
        LOGIN_BY_PASSWORD: 'member/login',
        VERIFY_BY_OTP: 'login/email-verify-code',
        SEND_OTP: 'login/email-resend-otp-code', // FOR RESEND OTP IN CASE FAIL
    },
    PHONE: {
        REGISTER_BY_SEND_OTP: 'login/login-with-sms',
        SEND_OTP: 'login/sms/sent-otp',
        VERIFY_BY_OTP: 'login/phone-verify-code',
        LOGIN_BY_PASSWORD: 'member/login-by-phone',
        UPDATE_PHONE_SEND_OTP: 'login/sms-social/sent-otp',
        UPDATE_PHONE_VERIFY_OTP: 'login/sms-social/phone-verify-code',
    },
    WHATSAPP: {
        LOGIN_OTP_WHATSAPP: 'login/login-otp-whatsapp',
        REGISTER_BY_SEND_OTP: 'login/login-with-whatsapp',
        SEND_OTP: 'login/whatsapp/sent-otp',
        UPDATE_PHONE_SEND_OTP: 'login/sms-social/whatsapp/sent-otp',
        UPDATE_PHONE_VERIFY_OTP: 'login/sms-social/whatsapp-verify-code',
        VERIFY_BY_OTP: 'login/whatsapp-verify-code',
    },
    ZALO: {
        REGISTER_BY_SEND_OTP: 'login/login-with-zalo',
        SEND_OTP: 'login/zalo/sent-otp',
        VERIFY_BY_OTP: 'login/zalo-verify-code',
        UPDATE_PHONE_SEND_OTP: 'login/sms-social/zalo/sent-otp',
        UPDATE_PHONE_VERIFY_OTP: 'login/sms-social/zalo-verify-code',
    },
    RESET_PASSWORD: 'login/reset-password',
    CHECK_USER_EXIST: 'member/check-user-exist',
    UPDATE_USER_INFO: 'login/update-first-info',
    SETUP_USER_INFO: 'login/setup-first-info',
    ECOM_CARE: {
        SEND_OTP: 'login/ecom-care/send-email-otp-code',
        VERIFY_OTP: 'login/ecom-care/email-verify-code',
        RESEND_OTP: 'login/ecom-care/resend-email-otp-code',
    },
};

// export const locale = process.env.NEXT_PUBLIC_DEPLOY_LOCALE || 'vi-VN'
const locale = process.env.NEXT_PUBLIC_DEPLOY_LOCALE || 'ms-MY';
const websiteId = {
    [Locale.LOCALE.Vietnam]: '1',
    [Locale.LOCALE.Indonesia]: '2',
    [Locale.LOCALE.Malaysia]: '3',
}[locale];
index.LOCALE_SPECS[locale].PHONE;
const getSSOV2ApiUrl = (path) => {
    return normalizeLink.normalizeLinkSlash(`${normalizeLink.getCurrentSsoUrl(locale)}/api/v2/${path}`);
};
const getSSOApiUrl = (path) => {
    return normalizeLink.normalizeLinkSlash(`${normalizeLink.getCurrentSsoUrl(locale)}/api/${path}`);
};
const BEARER_TOKEN_COOKIE = 'hhg_user_token';
// NOTICE: RUN ONLY CLIENT SIDE
const fetchSSOV2Api = (path, options = {}, noAuth) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
    var _a;
    let response;
    const authToken = noAuth
        ? ''
        : (_a = document.cookie
            .split('; ')
            .find((row) => row.startsWith(BEARER_TOKEN_COOKIE))) === null || _a === void 0 ? void 0 : _a.split('=')[1];
    try {
        if (options.body instanceof FormData) {
            options.body.append('ga_client_id', miscCookieHelper.getCookie('_ga') || '');
            options.body.append('referrer', window.location.href);
        }
        response = yield fetch(getSSOV2ApiUrl(path), authToken
            ? Object.assign(Object.assign({}, options), { headers: Object.assign({ Authorization: `Bearer ${authToken}` }, options === null || options === void 0 ? void 0 : options.headers) }) : options);
    }
    catch (error) {
        console.error(error);
        return null;
    }
    return response === null || response === void 0 ? void 0 : response.json();
});
/** JSON body (e.g. WhatsApp login-otp / verify-code); omits FormData-only ga/referrer append. */
const fetchSSOV2ApiJson = (path, body, noAuth) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
    var _b;
    let response;
    const authToken = noAuth
        ? ''
        : (_b = document.cookie
            .split('; ')
            .find((row) => row.startsWith(BEARER_TOKEN_COOKIE))) === null || _b === void 0 ? void 0 : _b.split('=')[1];
    try {
        response = yield fetch(getSSOV2ApiUrl(path), {
            method: 'POST',
            headers: Object.assign({ Accept: 'application/json', 'Content-Type': 'application/json' }, (authToken ? { Authorization: `Bearer ${authToken}` } : {})),
            body: JSON.stringify(body),
        });
    }
    catch (error) {
        console.error(error);
        return null;
    }
    return response === null || response === void 0 ? void 0 : response.json();
});
const fetchSSOApi = (path, options = {}, noAuth) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
    var _c;
    let response;
    const authToken = noAuth
        ? ''
        : (_c = document.cookie
            .split('; ')
            .find((row) => row.startsWith(BEARER_TOKEN_COOKIE))) === null || _c === void 0 ? void 0 : _c.split('=')[1];
    try {
        response = yield fetch(getSSOApiUrl(path), authToken
            ? Object.assign(Object.assign({}, options), { headers: Object.assign({ Authorization: `Bearer ${authToken}` }, options === null || options === void 0 ? void 0 : options.headers) }) : options);
    }
    catch (error) {
        console.error(error);
        return null;
    }
    return response === null || response === void 0 ? void 0 : response.json();
});
const resetPassword = (password, confirmPassword) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
    const formData = new FormData();
    formData.append('password', password);
    formData.append('confirm-password', confirmPassword);
    return fetchSSOV2Api(SSO_V2_PATHS.RESET_PASSWORD, {
        method: 'POST',
        body: formData,
    });
});
// "email":"kenny_test2201_11@mailinator.com"
// "phone_number":"906911910"
const checkUserExist = ({ email, phone, // no +
 }) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
    // "provider": "email",
    // "is_pass": true,
    // "is_status": "Active"
    const formData = new FormData();
    if (email) {
        formData.append('email', email);
    }
    else {
        formData.append('phone_number', phone);
    }
    return fetchSSOV2Api(SSO_V2_PATHS.CHECK_USER_EXIST, {
        method: 'POST',
        body: formData,
    });
});
// "name": "Huy Tran 888",
// "birthday": "1989-04-26",
// "email":"kenny_test2201_02@mailinator.com", // optional chỉ require khi source là care | ecom
// "password": "Kenny2103",
// "confirm_password":"Kenny2103",
// "phone_number":"906911912", // require khi user register bằng email hoặc social
// "area_code":"+84", // require khi có phone number
// "gender": 1,
// "validate": false,  // true validate sau khi validate xong truyền false để update
// "source": "care" | "ecom" // default sẽ ko require email. nếu source là care sẽ require email. ==> support cho business care
const updateUserInfo = (data) => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
    const formData = new FormData();
    Object.keys(data).forEach((key) => {
        const value = data[key];
        if (typeof value !== 'undefined' &&
            value !== null &&
            (typeof value !== 'string' || !!value.trim())) {
            formData.append(key, data[key]);
        }
    });
    return fetchSSOV2Api(SSO_V2_PATHS.SETUP_USER_INFO, {
        method: 'POST',
        body: formData,
    });
});
const GoogleAuthClientId = constantsIsProduction.isProduction
    ? '289442006438-040a42cbidr6v5d178f3iqi9q95821r3.apps.googleusercontent.com'
    : '289442006438-cihobuq1h3r4426pur7u0e43fqdnep59.apps.googleusercontent.com';
const FacebookAppId = '2759888574045636';
const getUserInfo = () => tslib_es6.__awaiter(void 0, void 0, void 0, function* () {
    return fetchSSOApi('user/profile', {
        method: 'POST',
    });
});
const handleAuthSuccess = (res) => {
    (res === null || res === void 0 ? void 0 : res.token) &&
        miscCookieHelper.setCookie(BEARER_TOKEN_COOKIE, res.token, {
            domain: window.location.hostname === 'localhost'
                ? 'localhost'
                : `.${constantsDomainLocales.domainLocales[locale]}`,
            expires: new Date(res.expire_in * 1000).toUTCString(),
        });
    (res === null || res === void 0 ? void 0 : res.refresh_token) &&
        miscCookieHelper.setCookie(index.BEARER_REFRESH_TOKEN_COOKIE, res.refresh_token, {
            domain: window.location.hostname === 'localhost'
                ? 'localhost'
                : `.${constantsDomainLocales.domainLocales[locale]}`,
        });
};

exports.BEARER_TOKEN_COOKIE = BEARER_TOKEN_COOKIE;
exports.FacebookAppId = FacebookAppId;
exports.GoogleAuthClientId = GoogleAuthClientId;
exports.SSO_V2_PATHS = SSO_V2_PATHS;
exports.checkUserExist = checkUserExist;
exports.fetchSSOV2Api = fetchSSOV2Api;
exports.fetchSSOV2ApiJson = fetchSSOV2ApiJson;
exports.getUserInfo = getUserInfo;
exports.handleAuthSuccess = handleAuthSuccess;
exports.locale = locale;
exports.resetPassword = resetPassword;
exports.updateUserInfo = updateUserInfo;
exports.websiteId = websiteId;
