"use strict";
exports.id = 269;
exports.ids = [269];
exports.modules = {

/***/ 4269:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {


// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "Z": () => (/* binding */ auth),
  "a": () => (/* binding */ useAuth)
});

// EXTERNAL MODULE: external "react/jsx-runtime"
var jsx_runtime_ = __webpack_require__(997);
// EXTERNAL MODULE: external "react"
var external_react_ = __webpack_require__(6689);
// EXTERNAL MODULE: external "next/router"
var router_ = __webpack_require__(1853);
// EXTERNAL MODULE: external "axios"
var external_axios_ = __webpack_require__(2167);
var external_axios_default = /*#__PURE__*/__webpack_require__.n(external_axios_);
;// CONCATENATED MODULE: ./utils/errorCode.ts
class HttpError extends Error {
    constructor(code, status){
        super(code);
        this.code = code;
        this.status = status;
    }
}
const errorCode = {
    LOGIN_FAILED: new HttpError("LOGIN_FAILED", 401),
    UNAUTHORIZED_REQUEST: new HttpError("UNAUTHORIZED_REQUEST", 401),
    RESPONSE_FORMAT_ERROR: new HttpError("RESPONSE_FORMAT_ERROR", 400)
};

;// CONCATENATED MODULE: ./lib/api.ts


var API;
(function(API1) {
    API1["Login"] = "/api/auth/login";
    API1["Logout"] = "/api/auth/logout";
    API1["Profile"] = "/api/auth/profile";
})(API || (API = {}));
/* harmony default export */ const api = (API);
const handleError = ({ statusCode , errorMessage  })=>{
    const errorCodeMap = {
        [errorCode.UNAUTHORIZED_REQUEST.status] () {
            localStorage.clear();
        },
        default () {
        //
        }
    };
    return (errorCodeMap[statusCode] || errorCodeMap["default"])();
};
const axiosInstance = external_axios_default().create({
    baseURL: process.env.API_URL || "http://localhost:4200",
    responseType: "json",
    timeout: 30000,
    headers: {
        "Content-Type": "application/json"
    }
});
axiosInstance.interceptors.response.use((response)=>response
, (error)=>{
    var ref;
    const { message  } = error;
    const { status: statusCode  } = error.response;
    var ref1;
    const { code  } = (ref1 = (ref = error.response) === null || ref === void 0 ? void 0 : ref.data) !== null && ref1 !== void 0 ? ref1 : "";
    console.error(`${code} ${error.config.baseURL}${error.config.url} ${message}`);
    if (code) handleError({
        statusCode,
        errorMessage: message
    });
    return Promise.reject(error);
});

// EXTERNAL MODULE: ./lib/path.ts
var path = __webpack_require__(9892);
;// CONCATENATED MODULE: ./lib/auth.tsx





const ACCESS_TOKEN_KEY = "session";
const REFRESH_TOKEN_KEY = "refreshToken";
const AuthContext = /*#__PURE__*/ (0,external_react_.createContext)(null);
const useAuth = ()=>{
    return (0,external_react_.useContext)(AuthContext);
};
const AuthProvider = ({ children  })=>{
    const router = (0,router_.useRouter)();
    const { 0: user , 1: setUser  } = (0,external_react_.useState)(null);
    const { 0: token , 1: setToken  } = (0,external_react_.useState)(null);
    const clearLoginInfo = ()=>{
        window.localStorage.removeItem(ACCESS_TOKEN_KEY);
        window.localStorage.removeItem(REFRESH_TOKEN_KEY);
        setToken(null);
        setUser(null);
    };
    const login = async ({ username , password  })=>{
        const response = await axiosInstance.post(api.Login, {
            username,
            password
        });
        const { profile , accessToken , refreshToken  } = response.data;
        window.localStorage.setItem(ACCESS_TOKEN_KEY, accessToken);
        window.localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken);
        setToken(accessToken);
        setUser(profile);
    };
    const logout = async ()=>{
        await axiosInstance.get(api.Logout, {
            headers: {
                Authorization: `Bearer ${token}`
            }
        });
        clearLoginInfo();
    };
    // check if user is logged in
    const getProfile = async (options)=>{
        try {
            const accessToken = window.localStorage.getItem(ACCESS_TOKEN_KEY) || token;
            setToken(accessToken);
            const { data  } = await axiosInstance.get(api.Profile, {
                headers: {
                    Authorization: `Bearer ${accessToken}`
                }
            });
            setUser(data.profile);
            // go to home page if auth is disabled
            if (data.profile === null) {
                if (router.pathname === path/* default.Login */.Z.Login) {
                    router.push(path/* default.Home */.Z.Home);
                }
            }
        } catch (e) {
            clearLoginInfo();
            options.redirectTo && router.push(options.redirectTo);
        }
    };
    const syncStorageSession = (event)=>{
        if (event.key === ACCESS_TOKEN_KEY) {
            setToken(event.newValue);
        }
    };
    const auth = {
        user,
        token,
        login,
        logout,
        getProfile,
        syncStorageSession
    };
    return /*#__PURE__*/ jsx_runtime_.jsx(AuthContext.Provider, {
        value: auth,
        children: children
    });
};
/* harmony default export */ const auth = (AuthProvider);


/***/ })

};
;