import type { PayloadAction } from "@reduxjs/toolkit";
import { createSlice } from "@reduxjs/toolkit";
import type { Token, UserData, UserDataAndToken } from "./types";

export interface AuthState {
	isAuthenticated: boolean;
	user: UserData;
	token: Token;
}

const initialState: AuthState = {
	isAuthenticated: false,
	user: {} as UserData,
	token: {} as Token,
};

export const authSlice = createSlice({
	name: "auth",
	initialState: initialState,
	reducers: {
		setToken: (state, action: PayloadAction<Token>) => {
			state.token = action.payload;
		},
		setUserData: (state, action: PayloadAction<UserData>) => {
			state.user = action.payload;
			state.isAuthenticated = true;
		},
		login: (state, action: PayloadAction<UserDataAndToken>) => {
			state.isAuthenticated = true;
			state.user = action.payload.user;
			state.token = action.payload.tokens;
		},
		logout: (state) => {
			state = initialState;
		},
	},
});

export const { login, logout, setToken, setUserData } = authSlice.actions;
export const authReducer = authSlice.reducer;
