import { type MembershipStatus } from './api-schemas.js'

export type { MembershipStatus }

/**
 * Organization Membership types based on WorkOS API
 */

export interface OrganizationMembership {
  object: 'organization_membership'
  id: string
  userId: string
  organizationId: string
  role: {
    slug: string
  }
  status: 'active' | 'inactive'
  createdAt: string
  updatedAt: string
}

/**
 * Request interfaces for membership operations
 */
export interface CreateMembershipRequest {
  userId: string
  organizationId: string
  roleSlug?: string
}

export interface UpdateMembershipRequest {
  roleSlug: string
}

export interface ListMembershipsParams {
  userId?: string
  organizationId?: string
  statuses?: MembershipStatus[]
  limit?: number
  before?: string
  after?: string
  order?: 'asc' | 'desc'
}

/**
 * Response interfaces
 */
export interface ListMembershipsResponse {
  data: OrganizationMembership[]
  listMetadata?: {
    before?: string | null
    after?: string | null
  }
}

/**
 * Extended membership with user and organization details for UI
 */
export interface MembershipWithDetails extends OrganizationMembership {
  user?: {
    id: string
    email: string
    firstName?: string
    lastName?: string
    profilePictureUrl?: string
  }
  organization?: {
    id: string
    name: string
    workos_org_id: string
    primaryDomain?: string
    is_test?: boolean
    status?: string
    metadata?: Record<string, unknown>
    config?: Record<string, unknown>
  }
}

/**
 * UI-specific membership table row data
 */
export interface MembershipTableRow {
  id: string
  userId: string
  organizationId: string
  userEmail: string
  userFullName: string
  organizationName: string
  role: string
  status: MembershipStatus
  statusBadge: 'active' | 'inactive'
  joinedAt: Date
  updatedAt: Date
  canEdit: boolean
  canRemove: boolean
}

/**
 * Transform membership to table row format
 */
export function transformMembershipToTableRow(membership: MembershipWithDetails): MembershipTableRow {
  return {
    id: membership.id,
    userId: membership.userId,
    organizationId: membership.organizationId,
    userEmail: membership.user?.email || 'Unknown',
    userFullName:
      membership.user?.firstName && membership.user?.lastName
        ? `${membership.user.firstName} ${membership.user.lastName}`
        : membership.user?.email || 'Unknown User',
    organizationName: membership.organization?.name || 'Unknown Organization',
    role: membership.role.slug,
    status: membership.status,
    statusBadge: membership.status,
    joinedAt: new Date(membership.createdAt),
    updatedAt: new Date(membership.updatedAt),
    canEdit: membership.status === 'active',
    canRemove: true
  }
}

/**
 * Membership status color mapping for UI
 */
export const MEMBERSHIP_STATUS_COLORS = {
  active: 'green',
  inactive: 'gray'
} as const
