import type { BackofficeRole } from '$lib/types/backoffice-user';

export type BackofficePermission = 'dashboard' | 'landing' | 'paket' | 'member' | 'users';

export const BACKOFFICE_ROLE_LABELS: Record<BackofficeRole, string> = {
	super_admin: 'Super Admin',
	admin: 'Admin',
	viewer: 'Viewer'
};

export const BACKOFFICE_ROLE_DESCRIPTIONS: Record<BackofficeRole, string> = {
	super_admin: 'Akses penuh termasuk kelola pengguna back office',
	admin: 'Kelola landing page, paket, dan member',
	viewer: 'Hanya lihat dashboard dan data member (tanpa edit)'
};

export const ROLE_PERMISSIONS: Record<BackofficeRole, BackofficePermission[]> = {
	super_admin: ['dashboard', 'landing', 'paket', 'member', 'users'],
	admin: ['dashboard', 'landing', 'paket', 'member'],
	viewer: ['dashboard', 'member']
};

export const BACKOFFICE_MENU_ITEMS: {
	label: string;
	href: string;
	icon: string;
	exact: boolean;
	permission: BackofficePermission;
}[] = [
	{ label: 'Dashboard', href: '/backoffice', icon: '📊', exact: true, permission: 'dashboard' },
	{ label: 'Landing Page', href: '/backoffice/landing', icon: '🌐', exact: false, permission: 'landing' },
	{ label: 'Paket Langganan', href: '/backoffice/paket', icon: '💎', exact: false, permission: 'paket' },
	{ label: 'Kelola Member', href: '/backoffice/member', icon: '👥', exact: false, permission: 'member' },
	{ label: 'Pengguna BO', href: '/backoffice/users', icon: '🔐', exact: false, permission: 'users' }
];

export const BACKOFFICE_ROLES = Object.keys(BACKOFFICE_ROLE_LABELS) as BackofficeRole[];

export function hasPermission(role: BackofficeRole, permission: BackofficePermission): boolean {
	return ROLE_PERMISSIONS[role]?.includes(permission) ?? false;
}

export function canWrite(role: BackofficeRole): boolean {
	return role !== 'viewer';
}

export function getMenuItemsForRole(role: BackofficeRole) {
	return BACKOFFICE_MENU_ITEMS.filter((item) => hasPermission(role, item.permission));
}

export function getRoutePermission(pathname: string): BackofficePermission | null {
	if (pathname === '/backoffice' || pathname === '/backoffice/') return 'dashboard';
	if (pathname.startsWith('/backoffice/landing')) return 'landing';
	if (pathname.startsWith('/backoffice/paket')) return 'paket';
	if (pathname.startsWith('/backoffice/member')) return 'member';
	if (pathname.startsWith('/backoffice/users')) return 'users';
	return null;
}
