// Use generated Supabase types from packages/core/src/types/supabase/database.types.ts
import type { TablesInsert, TablesUpdate } from '../../../supabase/database.types'
import type { OrganizationMembership } from './membership'
import type { SupabaseOrgMembership } from '../../../supabase'

// Re-export from centralized location for backward compatibility
export type { SupabaseOrgMembership } from '../../../supabase'

// Supabase org_memberships table types (auto-generated)
export type SupabaseOrgMembershipInsert = TablesInsert<'org_memberships'>
export type SupabaseOrgMembershipUpdate = TablesUpdate<'org_memberships'>

// Available fields from generated types:
// {
//   id: string
//   user_id: string
//   organization_id: string
//   workos_membership_id: string
//   membership_status: string | null (default: 'active')
//   role_slug: string | null (default: 'member')
//   created_at: string | null
//   updated_at: string | null
// }

/**
 * Map Supabase status to internal status.
 * Database constraint only allows 'active' | 'inactive'.
 */
function mapSupabaseStatus(status: string | null): 'active' | 'inactive' {
  if (status === 'active') return 'active'
  return 'inactive'
}

// Transform Supabase to internal format
export function transformSupabaseToMembership(supabaseData: SupabaseOrgMembership): OrganizationMembership {
  return {
    object: 'organization_membership',
    id: supabaseData.workos_membership_id ?? supabaseData.id,
    userId: supabaseData.user_id,  // Always use Supabase user_id
    organizationId: supabaseData.organization_id,  // Always use Supabase organization_id
    role: { slug: supabaseData.role_slug || 'member' },
    status: mapSupabaseStatus(supabaseData.membership_status),
    createdAt: supabaseData.created_at || new Date().toISOString(),
    updatedAt: supabaseData.updated_at || new Date().toISOString()
  }
}
