import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";

export const checkAuth = createAsyncThunk("auth/checkAuth", async () => {
    const token = localStorage.getItem("access_token");
    if (token) {
        return { token };
    }
    return null;
});

const initialState = {
    user: null,
    isLoading: true,
    error: null,
};

const authSlice = createSlice({
    name: "auth",
    initialState,
    reducers: {
        setUser(state, action) {
            state.user = action.payload;
            state.isLoading = false;
            state.error = null;
        },
        setError(state, action) {
            state.error = action.payload;
            state.isLoading = false;
        },
        logout(state) {
            state.user = null;
            state.error = null;
            state.isLoading = false;
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(checkAuth.fulfilled, (state, action) => {
                state.user = action.payload;
                state.isLoading = false;
            })
            .addCase(checkAuth.rejected, (state) => {
                state.isLoading = false;
            });
    },
});

export const { setUser, setError, logout } = authSlice.actions;
export default authSlice.reducer;