import { auth } from '@/lib/auth'
import { hasPermission, Permission } from '@/lib/services/permission-service'
import { StaffRole } from '@prisma/client'

export interface AuthenticatedStaffSession {
  user: {
    id: string
    email: string
    name?: string | null
    userType: 'staff'
    role: StaffRole
  }
}

/**
 * Require a staff session with specific permission
 * Returns the authenticated session or throws with error info
 */
export async function requireStaffPermission(
  permission: Permission
): Promise<AuthenticatedStaffSession> {
  const session = await auth()

  if (!session || !session.user) {
    throw { status: 401, message: 'Unauthorized' }
  }

  if (session.user.userType !== 'staff') {
    throw { status: 403, message: 'Staff access required' }
  }

  const role = session.user.role as StaffRole
  if (!hasPermission(role, permission)) {
    throw { status: 403, message: 'Insufficient permissions' }
  }

  return {
    user: {
      id: session.user.id,
      email: session.user.email || '',
      name: session.user.name,
      userType: 'staff',
      role,
    },
  }
}

/**
 * Require any authenticated staff session
 */
export async function requireStaffSession(): Promise<AuthenticatedStaffSession> {
  const session = await auth()

  if (!session || !session.user) {
    throw { status: 401, message: 'Unauthorized' }
  }

  if (session.user.userType !== 'staff') {
    throw { status: 403, message: 'Staff access required' }
  }

  return {
    user: {
      id: session.user.id,
      email: session.user.email || '',
      name: session.user.name,
      userType: 'staff',
      role: session.user.role as StaffRole,
    },
  }
}
