import type { WorkOSOrganization } from './workos'
import type { Organization } from '../organization'

/**
 * Transform WorkOS organization to our internal format
 */
export function transformWorkOSOrganization(
  workosOrg: WorkOSOrganization
): Organization {
  const verifiedDomains = workosOrg.domains
    .filter(d => d.state === 'verified' || d.state === 'legacy_verified')
    .map(d => d.domain)

  const pendingDomains = workosOrg.domains
    .filter(d => d.state === 'pending')
    .map(d => d.domain)

  const allDomains = workosOrg.domains.map(d => d.domain)

  return {
    workosId: workosOrg.id,
    name: workosOrg.name,
    domains: allDomains,
    createdAt: workosOrg.createdAt,
    updatedAt: workosOrg.updatedAt,
    stripeCustomerId: workosOrg.stripeCustomerId,
    externalId: workosOrg.externalId,
    workosMetadata: workosOrg.metadata,

    // Derived fields
    primaryDomain: verifiedDomains[0] || allDomains[0],
    verifiedDomains,
    pendingDomains
  }
}
