import { apiRequest } from '../lib/api'
import type { RolesListResponse } from '../types/user'

export interface AddTeamMemberPayload {
  cellNumber: string
  firstName: string
  lastName: string
  roleSlug: string
  email?: string
  password?: string
}

export async function listTeamRoles(signal?: AbortSignal) {
  return apiRequest<RolesListResponse>('/roles?scope=team', { auth: true, signal })
}

export async function addTeamMember(businessId: number | string, payload: AddTeamMemberPayload) {
  return apiRequest(`/businesses/${businessId}/team`, {
    method: 'POST',
    auth: true,
    body: payload,
  })
}

export async function updateTeamMemberRole(
  businessId: number | string,
  memberId: number | string,
  roleSlug: string,
) {
  return apiRequest(`/businesses/${businessId}/team/${memberId}`, {
    method: 'PATCH',
    auth: true,
    body: { roleSlug },
  })
}

export type BusinessAccess = 'customer' | 'staff'

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

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

/** Set customer vs staff (admin/editor/viewer) for a user on one business. */
export async function assignBusinessAccess(
  businessId: number | string,
  payload: AssignBusinessAccessPayload,
) {
  return apiRequest<AssignBusinessAccessResult>(`/businesses/${businessId}/team/access`, {
    method: 'PATCH',
    auth: true,
    body: {
      userId: String(payload.userId),
      access: payload.access,
      ...(payload.access === 'staff' && payload.roleSlug
        ? { roleSlug: payload.roleSlug }
        : {}),
    },
  })
}
