/**
 * saas-admin blueprint · wiring seam for `@platform-modules/tenancy`.
 *
 * Adapter-minimalism (CLAUDE.md §4): instantiate tenancy's real exports over the in-memory store
 * + a fake RBAC adapter, and seed the two-tenant fixture the composition test needs. The security
 * point the blueprint proves: resolveCapabilities(user, tenant) returns the EMPTY set unless the
 * user is an active member of an active tenant — so capabilities are tenant-scoped, and a caller
 * acting on a tenant they do not belong to is structurally unprivileged.
 */
import {
  createMemoryTenancyStore,
  createTenancy,
  type RbacAdapter,
  type Tenant,
  type Tenancy,
} from '@platform-modules/tenancy'

/** Fake RBAC: role → capabilities. A real host backs this with a roles/permissions table. */
export function createFakeRbac(roleCapabilities: Record<string, string[]>): RbacAdapter {
  return {
    async resolveCapabilities({ roleKey }) {
      return roleCapabilities[roleKey] ?? []
    },
  }
}

export type SeededTenancy = {
  tenancy: Tenancy
  /** tenant the admin is an active 'admin' member of */
  tenantA: Tenant
  /** tenant the admin is NOT a member of — the cross-tenant isolation target */
  tenantB: Tenant
  adminUserId: string
  memberUserId: string
}

/**
 * Seed: tenant A (Acme) with an active admin + an active plain member; tenant B (Globex) where the
 * same admin has NO membership. The role→capability map gives 'admin' the suspend capability and
 * 'member' only read.
 */
export async function seedTenancy(): Promise<SeededTenancy> {
  const store = createMemoryTenancyStore()
  const rbac = createFakeRbac({
    admin: ['member:read', 'member:suspend'],
    member: ['member:read'],
  })
  const tenancy = createTenancy({ store, rbac })

  const adminUserId = 'u-admin'
  const memberUserId = 'u-member'

  const tenantA = await tenancy.createTenant({ slug: 'acme', name: 'Acme', ownerId: adminUserId })
  const tenantB = await tenancy.createTenant({ slug: 'globex', name: 'Globex', ownerId: 'u-other' })

  await tenancy.addMember({ tenantId: tenantA.id, userId: adminUserId, roleKey: 'admin', status: 'active' })
  await tenancy.addMember({ tenantId: tenantA.id, userId: memberUserId, roleKey: 'member', status: 'active' })

  return { tenancy, tenantA, tenantB, adminUserId, memberUserId }
}
