import { IMovie } from "@autoplex-api/request";
import { GetterTree } from "vuex";
import { IState } from "./state";

export type GettersTypes = {
	isAdmin        (state: IState): boolean,
	isAuthenticated(state: IState): boolean,
	storedToken    ()             : string | null,
	token          (state: IState): string | null,
	userName       (state: IState): string | null,

	// Movie Store
	movies(state: IState): (movies: IMovie[]) => IMovie[]
}

export const getters: GettersTypes & GetterTree<IState, IState> = {
	/**
	 * Determine if the current user is authenticated
	 */
	isAuthenticated(state: IState) {
		return state.user != null;
	},

	/**
	 * Determine if the user is an admin
	 */
	isAdmin(state: IState) {
		return state.user?.isAdmin ?? false;
	},

	/**
	 * Retrieve the stored token
	 */
	storedToken() {
		return sessionStorage.getItem("jwt") ?? localStorage.getItem("jwt");
	},

	/**
	 * Get the current token
	 */
	token(state: IState) {
		return state.user?.token ?? null;
	},

	/**
	 * Retrieve the user's ID
	 */
	userId(state: IState) {
		return state.user?.id;
	},

	/**
	 * Get the user's name (assumes authenticated)
	 */
	userName(state: IState) {
		return state.user?.name.split(" ")[0] ?? null;
	},

	// Movie Store ---------------------------------------------------------------------------------

	movies: (state: IState) => (movies: IMovie[]) => {
		return movies.map(movie => state.movies[movie.tmdbId].movie);
	}
};
