import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'

export type BusinessAccess = 'customer' | 'staff'

export interface AssignBusinessAccessPayload {
  userId: string
  access: BusinessAccess
  roleSlug?: string
}

export interface AssignBusinessAccessResult {
  message: string
  access: BusinessAccess
  member: {
    id: string | number
    userId: string | number
    isOwner: boolean
    teamRole: string | null
  } | null
}

function teamPath(suffix = '') {
  const businessId = getActiveBusinessId()
  if (!businessId) {
    throw new Error('No active business selected. Please sign in again.')
  }
  return `/businesses/${businessId}/team${suffix}`
}

/** Set customer vs manager (admin/editor/viewer) for a user on this business. */
export async function assignBusinessAccess(payload: AssignBusinessAccessPayload) {
  return apiRequest<AssignBusinessAccessResult>(teamPath('/access'), {
    method: 'PATCH',
    auth: true,
    body: {
      userId: String(payload.userId),
      access: payload.access,
      ...(payload.access === 'staff' && payload.roleSlug
        ? { roleSlug: payload.roleSlug }
        : {}),
    },
  })
}
