/**
 * commerce-storefront blueprint · wiring seam for `@platform-modules/auth`.
 *
 * Single-seller roles: guest (no session) · customer · merchant · owner. A real host injects a
 * JWT/DB-backed AuthEngine; this fake proves verifySession + role-bearing principals compose.
 */
import type { AuthEngine, Principal } from '@platform-modules/auth'
import { bearer, createFakeAuthEngine } from '../../community/wiring/auth.js'

export type StorefrontRole = 'guest' | 'customer' | 'merchant' | 'owner'

export type StorefrontAuth = {
  engine: AuthEngine
  sessions: Map<string, Principal>
  bearer: typeof bearer
  /** Seed a session token for a storefront role (test helper). */
  seedRole(token: string, role: Exclude<StorefrontRole, 'guest'>): Principal
}

const ROLE_CAPABILITIES: Record<Exclude<StorefrontRole, 'guest'>, string[]> = {
  customer: ['catalog:read', 'order:create', 'account:read'],
  merchant: ['catalog:read', 'catalog:write', 'order:read', 'order:write', 'admin:access'],
  owner: ['catalog:read', 'catalog:write', 'order:read', 'order:write', 'admin:access', 'store:settings'],
}

export function createStorefrontAuth(_db: unknown): StorefrontAuth {
  const sessions = new Map<string, Principal>()

  return {
    engine: createFakeAuthEngine(sessions),
    sessions,
    bearer,
    seedRole(token, role) {
      const principal: Principal = {
        userId: `u-${role}`,
        sessionId: `s-${role}`,
        roles: [role],
        capabilities: ROLE_CAPABILITIES[role],
      }
      sessions.set(token, principal)
      return principal
    },
  }
}
