import type { DeepPartial, OrganizationModel } from '../organization-model/published'
import { OrganizationModelSchema, resolveOrganizationModel } from '../organization-model/published'
import type { SupabaseUserProfile } from '../supabase'
import { createTestUser } from './fixtures'

export interface TestInitializationError {
  layer: 'auth' | 'profile' | 'organization'
  message: string
  originalError?: Error
}

export interface TestInitializationState {
  userReady: boolean
  organizationReady: boolean
  allReady: boolean
  isInitializing: boolean
  error: TestInitializationError | null
  retry: () => void
  profile: SupabaseUserProfile | null
}

export type TestInitializationStateOverrides = Partial<
  Omit<TestInitializationState, 'error' | 'profile' | 'retry'>
> & {
  error?: TestInitializationError | null
  profile?: Partial<SupabaseUserProfile> | SupabaseUserProfile | null
  retry?: () => void
}

export function makeOrganizationModel(
  overrides?: DeepPartial<OrganizationModel>
): OrganizationModel {
  return OrganizationModelSchema.parse(resolveOrganizationModel(overrides))
}

export function makeUserProfile(
  overrides: Partial<SupabaseUserProfile> = {}
): SupabaseUserProfile {
  return createTestUser(overrides)
}

export function makeInitializationState(
  overrides: TestInitializationStateOverrides = {}
): TestInitializationState {
  const defaultState: TestInitializationState = {
    userReady: true,
    organizationReady: true,
    allReady: true,
    isInitializing: false,
    error: null,
    retry: () => undefined,
    profile: makeUserProfile()
  }

  return {
    ...defaultState,
    ...overrides,
    profile:
      overrides.profile === undefined
        ? defaultState.profile
        : overrides.profile === null
          ? null
        : makeUserProfile(overrides.profile)
  }
}
