/**
 * Permissions abstraction layer
 *
 * Phase 1: Role-based logic (current)
 * Phase 2: Swap to Keto API calls
 *
 * Keto-compatible naming convention:
 * - service:<uuid>#assigned@team_profile:<uuid>
 * - service:<uuid>#viewer@customer_profile:<uuid>
 * - account:<uuid>#owner@customer:<uuid>
 */

import type { User } from '../app';

// Resource types in the system
export type Resource =
	| 'service'
	| 'project'
	| 'account'
	| 'customer'
	| 'report'
	| 'invoice'
	| 'scope'
	| 'profile';

// Actions that can be performed
export type Action = 'view' | 'edit' | 'delete' | 'manage' | 'session' | 'create';

/**
 * Check if a user can perform an action on a resource
 *
 * @param user - The current user
 * @param action - The action to check
 * @param resource - The resource type
 * @param resourceId - Optional specific resource ID (for future Keto integration)
 */
export function can(
	user: User | null,
	action: Action,
	resource: Resource,
	resourceId?: string
): boolean {
	if (!user) return false;

	// Customer profiles: view only
	if (user.__typename === 'CustomerProfileType') {
		return action === 'view';
	}

	// Team profiles
	if (user.__typename === 'TeamProfileType') {
		// ADMIN and TEAM_LEADER: full access
		if (user.role === 'ADMIN' || user.role === 'TEAM_LEADER') {
			return true;
		}

		// TEAM_MEMBER: view and session only
		if (user.role === 'TEAM_MEMBER') {
			return action === 'view' || action === 'session';
		}
	}

	return false;
}

/**
 * Check if user can see internal-flagged content (notes, photos, videos)
 * Only team members can see internal content
 */
export function canSeeInternal(user: User | null): boolean {
	return user?.__typename === 'TeamProfileType';
}

/**
 * Check if user can access admin routes
 */
export function canAccessAdmin(user: User | null): boolean {
	if (!user) return false;
	if (user.__typename !== 'TeamProfileType') return false;
	return user.role === 'ADMIN' || user.role === 'TEAM_LEADER';
}

/**
 * Check if user can access portal routes
 * All authenticated users can access portal
 */
export function canAccessPortal(user: User | null): boolean {
	return user !== null;
}

/**
 * Check if user is assigned to a service/project
 * Used for determining session edit permissions
 */
export function isAssignedTo(
	userId: string,
	teamMembers: Array<{ teamProfileId: string }> | null | undefined
): boolean {
	if (!teamMembers) return false;
	return teamMembers.some((m) => m.teamProfileId === userId);
}

/**
 * Build permissions context object for passing to layouts/components
 */
export function buildPermissions(user: User | null) {
	return {
		// Resource permissions
		canManageServices: can(user, 'manage', 'service'),
		canManageProjects: can(user, 'manage', 'project'),
		canManageAccounts: can(user, 'manage', 'account'),
		canManageCustomers: can(user, 'manage', 'customer'),
		canManageInvoices: can(user, 'manage', 'invoice'),
		canManageScopes: can(user, 'manage', 'scope'),
		canManageProfiles: can(user, 'manage', 'profile'),
		canManageReports: can(user, 'manage', 'report'),

		// Session permissions (team members can interact with sessions)
		canEditSessions: can(user, 'session', 'service'),

		// Content visibility
		canSeeInternal: canSeeInternal(user),

		// Route access
		canAccessAdmin: canAccessAdmin(user),
		canAccessPortal: canAccessPortal(user),

		// User info for convenience
		isTeamProfile: user?.__typename === 'TeamProfileType',
		isCustomerProfile: user?.__typename === 'CustomerProfileType',
		isAdmin: user?.__typename === 'TeamProfileType' && user.role === 'ADMIN',
		isTeamLeader: user?.__typename === 'TeamProfileType' && user.role === 'TEAM_LEADER',
		isTeamMember: user?.__typename === 'TeamProfileType' && user.role === 'TEAM_MEMBER'
	};
}

export type Permissions = ReturnType<typeof buildPermissions>;
