'use server'

import {auth} from '@/auth'
import {
	Access,
	AllRolesPermissions,
	PERMISSIONS,
	type Permission,
	type SingedInSession
} from '@/lib/permission'

export type CanAccessResponse = {can: boolean; session: SingedInSession | null}
export type CanResponse = boolean | CanAccessResponse

const can = async (permission: Permission): Promise<CanResponse> => {
	const session: SingedInSession = (await auth()) as SingedInSession

	if (!session) return false

	const able =
		PERMISSIONS[session.user.role as keyof AllRolesPermissions].includes(
			permission
		)

	return !Object.values(Access).includes(permission as Access)
		? able
		: {can: able, session}
}

export default can
