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: {
		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 } = authSlice.actions;
export const authReducer = authSlice.reducer;
