Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

53.7 KB
Raw Blame
import { act, configure, fireEvent, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { platformComponents as components } from 'api-types'
import { FeatureFlagContext } from 'common'
import { mockAnimationsApi } from 'jsdom-testing-mocks'
import { HttpResponse } from 'msw'
import { toast } from 'sonner'
import { beforeEach, describe, expect, test, vi } from 'vitest'

import { AUTO_ENABLE_RLS_EVENT_TRIGGER_SQL } from '@/components/interfaces/Database/Triggers/EventTriggersList/EventTriggers.constants'
import { FGA_PERMISSIONS } from '@/hooks/misc/useCheckPermissionsV2'
import { createMockOrganizationResponse } from '@/tests/helpers'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
import { createMockProfileContext } from '@/tests/lib/profile-helpers'
import { routerMock } from '@/tests/lib/route-mock'

type OrganizationResponse = components['schemas']['OrganizationResponse_Output']
type PermissionsV2Response = components['schemas']['UserPermissionsResponse_Output']
type CreateProjectBody = components['schemas']['CreateProjectBody']
type CreateProjectResponse = components['schemas']['CreateProjectResponse_Output']
type RegionsInfo = components['schemas']['RegionsInfoPlatform_Output']
type MemberWithFreeProjectLimit = components['schemas']['MemberWithFreeProjectLimit_Output']
type OverdueInvoiceCount = components['schemas']['OverdueInvoiceCount_Output']
type OrganizationProjectsResponse = components['schemas']['OrganizationProjectsResponse_Output']
type Entitlement = components['schemas']['ListEntitlementsResponse_Output']['entitlements'][number]
type AvailableVersion = {
  postgres_engine: '15' | '17' | '17-oriole'
  release_channel: 'internal' | 'alpha' | 'beta' | 'ga' | 'withdrawn' | 'preview'
  version: string
}
type GitHubRepositoriesResponse = {
  partial_response_due_to_sso: boolean
  repositories: { id: number; installation_id: number; name: string; default_branch: string }[]
}

mockAnimationsApi()

// defaultHidden skips RTL's per-element accessibility (getComputedStyle) check, which makes
// each *ByRole query on this large form ~3x cheaper. Radix Selects also render hidden native
// <option>s, so option queries are scoped to the open listbox via findOption.
configure({ asyncUtilTimeout: 5000, defaultHidden: true })
vi.setConfig({ testTimeout: 30000 })

vi.mock('sonner', () => ({
  toast: { error: vi.fn(), success: vi.fn() },
}))

vi.mock('@/lib/password-strength', () => ({
  passwordNeedsPercentEncoding: () => false,
  passwordStrength: async (value: string) =>
    value.length >= 12
      ? { message: 'This password is strong.', warning: '', strength: 4 }
      : {
          message: 'This password is not secure enough.',
          warning: 'This password is not secure enough. You need a stronger password.',
          strength: 1,
        },
}))

vi.mock('@/lib/telemetry/track', () => ({ useTrack: () => vi.fn() }))

vi.mock(import('common'), async (importOriginal) => {
  const actual = await importOriginal()
  return {
    ...actual,
    useParams: () => ({ slug: 'default-org' }),
    useIsLoggedIn: () => true,
  }
})

vi.mock(import('@/lib/constants'), async (importOriginal) => {
  const actual = await importOriginal()
  return {
    ...actual,
    IS_PLATFORM: true,
  }
})

const ORG_SLUG = 'default-org'

const ADMIN_PERMISSIONS: PermissionsV2Response = {
  organizations: [
    {
      slug: ORG_SLUG,
      role: 'administrator',
      permissions: [
        FGA_PERMISSIONS.ORGANIZATION.PROJECTS_CREATE,
        FGA_PERMISSIONS.ORGANIZATION.CONFIG_WRITE,
      ],
      projects: [],
    },
  ],
}

const DEFAULT_AVAILABLE_REGIONS: RegionsInfo = {
  all: {
    smartGroup: [{ code: 'americas', name: 'Americas', type: 'smartGroup' }],
    specific: [
      { code: 'us-east-1', name: 'East US (North Virginia)', provider: 'AWS', type: 'specific' },
    ],
  },
  recommendations: {
    smartGroup: { code: 'americas', name: 'Americas', type: 'smartGroup' },
    specific: [
      { code: 'us-east-1', name: 'East US (North Virginia)', provider: 'AWS', type: 'specific' },
    ],
  },
}

const FRANKFURT = 'Central EU (Frankfurt)'
const SAO_PAULO = 'South America (São Paulo)'

const AVAILABLE_REGIONS_WITH_AUTO: RegionsInfo = {
  ...DEFAULT_AVAILABLE_REGIONS,
  all: {
    ...DEFAULT_AVAILABLE_REGIONS.all,
    auto: { code: 'auto', name: 'Auto', type: 'auto' },
  },
  recommendations: {
    ...DEFAULT_AVAILABLE_REGIONS.recommendations,
    auto: { code: 'auto', name: 'Auto', type: 'auto' },
  },
}

const availableRegionsWithSaoPaulo = (status?: 'capacity' | 'other'): RegionsInfo => ({
  ...DEFAULT_AVAILABLE_REGIONS,
  all: {
    ...DEFAULT_AVAILABLE_REGIONS.all,
    specific: [
      ...DEFAULT_AVAILABLE_REGIONS.all.specific,
      { code: 'sa-east-1', name: SAO_PAULO, provider: 'AWS', type: 'specific', status },
    ],
  },
})

const AVAILABLE_REGIONS_WITH_FRANKFURT: RegionsInfo = {
  ...DEFAULT_AVAILABLE_REGIONS,
  all: {
    ...DEFAULT_AVAILABLE_REGIONS.all,
    specific: [
      ...DEFAULT_AVAILABLE_REGIONS.all.specific,
      { code: 'eu-central-1', name: FRANKFURT, provider: 'AWS', type: 'specific' },
    ],
  },
}

const DEFAULT_AVAILABLE_VERSIONS: { available_versions: AvailableVersion[] } = {
  available_versions: [
    { postgres_engine: '15', release_channel: 'ga', version: 'supabase-postgres-15.6.1.139' },
    { postgres_engine: '17', release_channel: 'beta', version: 'supabase-postgres-17.9.9.999' },
    {
      postgres_engine: '17-oriole',
      release_channel: 'beta',
      version: 'supabase-postgres-17.9.9.999-orioledb',
    },
  ],
}

const DEFAULT_ENTITLEMENTS: Entitlement[] = [
  {
    feature: { key: 'integrations.github_connections', type: 'boolean' },
    hasAccess: false,
    type: 'boolean',
    config: { enabled: false },
  } as Entitlement,
  {
    feature: { key: 'instances.high_availability', type: 'boolean' },
    hasAccess: true,
    type: 'boolean',
    config: { enabled: true },
  } as Entitlement,
]

const EMPTY_ORG_PROJECTS: OrganizationProjectsResponse = {
  pagination: { count: 0, limit: 96, offset: 0 },
  projects: [],
}

const mockOrg = (overrides: Partial<OrganizationResponse> = {}) =>
  createMockOrganizationResponse({
    id: 1,
    slug: ORG_SLUG,
    name: 'Acme',
    plan: { id: 'pro', name: 'Pro' },
    ...overrides,
  })

function mockWizardEndpoints(
  overrides: {
    organizations?: OrganizationResponse[]
    permissions?: PermissionsV2Response
    freeProjectLimitMembers?: MemberWithFreeProjectLimit[]
    overdueInvoices?: OverdueInvoiceCount[]
    orgProjects?: OrganizationProjectsResponse
    availableRegions?: RegionsInfo | 'error'
    availableVersions?: { available_versions: AvailableVersion[] }
    entitlements?: Entitlement[]
    githubAuthorization?: object | null
    githubRepositories?: GitHubRepositoriesResponse
  } = {}
) {
  addAPIMock({
    method: 'get',
    path: '/platform/organizations',
    response: () =>
      HttpResponse.json<OrganizationResponse[]>(overrides.organizations ?? [mockOrg()]),
  })
  addAPIMock({
    method: 'get',
    path: '/platform/organizations/:slug',
    response: {
      ...(overrides.organizations?.[0] ?? mockOrg()),
      created_at: '2026-01-01T00:00:00Z',
      has_oriole_project: false,
    },
  })
  addAPIMock({
    method: 'get',
    path: '/platform/profile/permissions/v2',
    response: () =>
      HttpResponse.json<PermissionsV2Response>(overrides.permissions ?? ADMIN_PERMISSIONS),
  })
  addAPIMock({
    method: 'get',
    path: '/platform/organizations/:slug/members/reached-free-project-limit',
    response: () =>
      HttpResponse.json<MemberWithFreeProjectLimit[]>(overrides.freeProjectLimitMembers ?? []),
  })
  addAPIMock({
    method: 'get',
    path: '/platform/stripe/invoices/overdue',
    response: () => HttpResponse.json<OverdueInvoiceCount[]>(overrides.overdueInvoices ?? []),
  })
  addAPIMock({
    method: 'get',
    path: '/platform/organizations/:slug/oauth/apps',
    // @ts-expect-error - response shape not in generated paths type
    response: () => HttpResponse.json([]),
  })
  addAPIMock({
    method: 'get',
    path: '/platform/organizations/:slug/projects',
    response: () =>
      HttpResponse.json<OrganizationProjectsResponse>(overrides.orgProjects ?? EMPTY_ORG_PROJECTS),
  })
  const availableRegions = overrides.availableRegions
  if (availableRegions === 'error') {
    addAPIMock({
      method: 'get',
      path: '/platform/projects/available-regions',
      response: () =>
        HttpResponse.json<APIErrorBody>({ message: 'Failed to load regions' }, { status: 500 }),
    })
  } else {
    addAPIMock({
      method: 'get',
      path: '/platform/projects/available-regions',
      response: () => HttpResponse.json<RegionsInfo>(availableRegions ?? DEFAULT_AVAILABLE_REGIONS),
    })
  }
  addAPIMock({
    method: 'post',
    path: '/platform/organizations/:slug/available-versions',
    response: () =>
      HttpResponse.json<{ available_versions: AvailableVersion[] }>(
        overrides.availableVersions ?? DEFAULT_AVAILABLE_VERSIONS
      ),
  })
  addAPIMock({
    method: 'get',
    path: '/platform/organizations/:slug/entitlements',
    response: () =>
      HttpResponse.json<{ entitlements: Entitlement[] }>({
        entitlements: overrides.entitlements ?? DEFAULT_ENTITLEMENTS,
      }),
  })
  addAPIMock({
    method: 'get',
    path: '/platform/integrations/github/authorization',
    // @ts-expect-error - authorization payload isn't inspected beyond truthiness
    response: () => HttpResponse.json(overrides.githubAuthorization ?? null),
  })
  addAPIMock({
    method: 'get',
    path: '/platform/integrations/github/repositories',
    response: () =>
      HttpResponse.json<GitHubRepositoriesResponse>(
        overrides.githubRepositories ?? { partial_response_due_to_sso: false, repositories: [] }
      ),
  })
}

const DEFAULT_FLAGS = {
  disableProjectCreationAndUpdate: false,
  newProjectInternalOnlyConfiguration: false,
  disableOrioleProjectCreation: false,
  defaultRegionRestrictedPool: false,
  projectCreationRestrictedRegions: false,
  freeTierGeneralRegionEnrollment: false,
  freeTierGeneralRegionSelection: false,
}

async function renderWizard(
  options: { flags?: Record<string, boolean | string>; isConfigCatStale?: boolean } = {}
) {
  const { default: Wizard } = await import('@/pages/new/[slug]')
  return customRender(
    <FeatureFlagContext.Provider
      value={{
        configcat: { ...DEFAULT_FLAGS, ...options.flags },
        posthog: {},
        hasLoaded: true,
        isConfigCatStale: options.isConfigCatStale,
      }}
    >
      <Wizard dehydratedState={undefined} />
    </FeatureFlagContext.Provider>,
    { profileContext: createMockProfileContext() }
  )
}

const mockCreateProject = (onRequest?: (body: CreateProjectBody) => void) => {
  addAPIMock({
    method: 'post',
    path: '/platform/projects',
    response: async ({ request }) => {
      const body = (await request.json()) as CreateProjectBody
      onRequest?.(body)
      return HttpResponse.json<CreateProjectResponse>(
        {
          anon_key: 'anon-key',
          cloud_provider: 'AWS',
          endpoint: 'https://new-project-ref.supabase.co',
          id: 99,
          inserted_at: new Date(0).toISOString(),
          is_branch_enabled: false,
          is_physical_backups_enabled: false,
          name: body.name,
          organization_id: 1,
          organization_slug: ORG_SLUG,
          preview_branch_refs: [],
          ref: 'new-project-ref',
          region: 'us-east-1',
          service_key: 'service-key',
          status: 'COMING_UP',
          subscription_id: null,
        },
        { status: 201 }
      )
    },
  })
}

let user: ReturnType<typeof userEvent.setup>

// The ProjectCreation Selects don't associate their label with the trigger, so scope to
// the combobox via the shared FormLayout row instead of getByRole('combobox', { name }).
const getSelectTriggerByLabel = (labelText: string) => {
  const label = screen.getByText(labelText)
  const row = label.closest('[data-formlayout-id="labelContainer"]')?.parentElement
  const trigger = row?.querySelector('[role="combobox"]')
  if (!trigger) throw new Error(`No combobox trigger found near label "${labelText}"`)
  return trigger as HTMLElement
}

const submitAndReadRegionSelection = async (onRequest: ReturnType<typeof vi.fn>) => {
  fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))
  await waitFor(() => expect(onRequest).toHaveBeenCalled())
  return onRequest.mock.calls[0][0].region_selection
}

const findOption = async (name: string | RegExp) =>
  within(await screen.findByRole('listbox')).findByRole('option', { name })

const selectRegion = async (optionName: string | RegExp) => {
  await user.click(getSelectTriggerByLabel('Region'))
  await user.click(await findOption(optionName))
}

const fillProjectName = async (name: string) => {
  // Typing character-by-character re-renders the whole wizard per keystroke; the input
  // behaviour isn't under test, so set the value in one change event.
  fireEvent.change(await screen.findByPlaceholderText('Project name'), {
    target: { value: name },
  })
}

const generateAndWaitForStrongPassword = async () => {
  fireEvent.click(await screen.findByRole('button', { name: 'Generate a password' }))
  await waitFor(() =>
    expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '100')
  )
}

describe('project creation wizard', () => {
  beforeEach(() => {
    user = userEvent.setup({ delay: null })
    routerMock.setCurrentUrl(`/new/${ORG_SLUG}`)
  })

  test('creates a project on the happy path for a paid-plan organization', async () => {
    mockWizardEndpoints()
    const onRequest = vi.fn()
    mockCreateProject(onRequest)

    await renderWizard()

    await fillProjectName('My New Project')
    await generateAndWaitForStrongPassword()
    // The recommended region is preselected, so no manual region choice is needed
    expect(getSelectTriggerByLabel('Region')).toHaveTextContent('Americas')

    fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

    await waitFor(() => expect(onRequest).toHaveBeenCalled())
    expect(screen.queryByText('Confirm compute costs')).not.toBeInTheDocument()

    const body = onRequest.mock.calls[0][0]
    expect(body.name).toBe('My New Project')
    expect(body.organization_slug).toBe(ORG_SLUG)
    expect(body.desired_instance_size).toBe('micro')
    expect(body.region_selection).toMatchObject({ name: 'Americas' })

    await waitFor(() => expect(routerMock.asPath).toBe('/project/new-project-ref'))
  })

  test('omits the desired instance size for a free-plan organization', async () => {
    mockWizardEndpoints({
      organizations: [mockOrg({ plan: { id: 'free', name: 'Free' } })],
    })
    const onRequest = vi.fn()
    mockCreateProject(onRequest)

    await renderWizard()

    await screen.findByPlaceholderText('Project name')
    expect(screen.queryByText('Select a compute size')).not.toBeInTheDocument()

    await fillProjectName('Free Plan Project')
    await generateAndWaitForStrongPassword()
    fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

    await waitFor(() => expect(onRequest).toHaveBeenCalled())
    expect(onRequest.mock.calls[0][0].desired_instance_size).toBeUndefined()
  })

  describe('blocking states', () => {
    test('shows a warning and hides project fields when free-plan members exceed the project limit', async () => {
      mockWizardEndpoints({
        organizations: [mockOrg({ plan: { id: 'free', name: 'Free' } })],
        freeProjectLimitMembers: [
          { free_project_limit: 2, primary_email: '[email protected]', username: 'member-1' },
        ],
      })
      addAPIMock({ method: 'get', path: '/platform/organizations/:slug/members', response: [] })
      addAPIMock({
        method: 'get',
        path: '/platform/organizations/:slug/members/invitations',
        response: { invitations: [] },
      })
      addAPIMock({
        method: 'get',
        path: '/platform/organizations/:slug/roles',
        response: { org_scoped_roles: [], project_scoped_roles: [] },
      })

      await renderWizard()

      await screen.findByText(
        'The organization has members who have exceeded their free project limits'
      )
      expect(screen.getByText(/member-1 \(Limit: 2 free projects\)/)).toBeInTheDocument()
      expect(screen.queryByPlaceholderText('Project name')).not.toBeInTheDocument()
    })

    test('shows an admonition and hides project fields when the organization has overdue invoices', async () => {
      mockWizardEndpoints({
        overdueInvoices: [{ organization_id: 1, overdue_invoice_count: 1 }],
      })

      await renderWizard()

      await screen.findByText('Your organization has overdue invoices')
      expect(screen.getByRole('link', { name: 'View invoices' })).toHaveAttribute(
        'href',
        `/org/${ORG_SLUG}/billing#invoices`
      )
      expect(screen.queryByPlaceholderText('Project name')).not.toBeInTheDocument()
    })

    test('shows an incident warning and hides the whole form when project creation is disabled', async () => {
      mockWizardEndpoints()

      await renderWizard({ flags: { disableProjectCreationAndUpdate: true } })

      await screen.findByText('Project creation is currently disabled')
      expect(screen.queryByPlaceholderText('Project name')).not.toBeInTheDocument()
    })
  })

  describe('region selection', () => {
    test('blocks submission until a region is selected', async () => {
      mockWizardEndpoints({
        availableRegions: {
          ...DEFAULT_AVAILABLE_REGIONS,
          recommendations: {
            ...DEFAULT_AVAILABLE_REGIONS.recommendations,
            smartGroup: { code: 'americas', name: '', type: 'smartGroup' },
          },
        },
      })
      const onRequest = vi.fn()
      mockCreateProject(onRequest)

      await renderWizard()

      await fillProjectName('Region Required Project')
      await generateAndWaitForStrongPassword()
      expect(getSelectTriggerByLabel('Region')).toHaveTextContent('Select a region')

      fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

      expect(await screen.findByText('Please select a region.')).toBeInTheDocument()
      expect(onRequest).not.toHaveBeenCalled()

      await selectRegion(/Americas/)

      const regionSelection = await submitAndReadRegionSelection(onRequest)
      expect(regionSelection).toMatchObject({ name: 'Americas' })
    })

    test('defaults to the first general region when there is no recommendation', async () => {
      mockWizardEndpoints({
        availableRegions: { ...DEFAULT_AVAILABLE_REGIONS, recommendations: {} },
      })

      await renderWizard()

      await waitFor(() => expect(getSelectTriggerByLabel('Region')).toHaveTextContent('Americas'))
    })

    test('defaults to the recommended Auto option and submits it as an auto region selection', async () => {
      mockWizardEndpoints({ availableRegions: AVAILABLE_REGIONS_WITH_AUTO })
      const onRequest = vi.fn()
      mockCreateProject(onRequest)

      await renderWizard()

      await fillProjectName('Auto Region Project')
      await generateAndWaitForStrongPassword()
      await waitFor(() => expect(getSelectTriggerByLabel('Region')).toHaveTextContent('Auto'))

      // Only Auto carries the "Recommended" badge while it is recommended
      await user.click(getSelectTriggerByLabel('Region'))
      const autoOption = await findOption(/Auto/)
      expect(within(autoOption).getByText('Recommended')).toBeInTheDocument()
      const americasOption = within(screen.getByRole('listbox')).getByRole('option', {
        name: /Americas/,
      })
      expect(within(americasOption).queryByText('Recommended')).not.toBeInTheDocument()
      await user.click(autoOption)

      const regionSelection = await submitAndReadRegionSelection(onRequest)
      expect(regionSelection).toMatchObject({ code: 'auto', type: 'auto' })
    })

    describe('specific regions behind a link', () => {
      const FREE_PLAN_ORG = [mockOrg({ plan: { id: 'free', name: 'Free' } })]

      test('opens on the general regions alone for a free-plan org', async () => {
        mockWizardEndpoints({ organizations: FREE_PLAN_ORG })

        await renderWizard()

        await screen.findByPlaceholderText('Project name')
        await user.click(getSelectTriggerByLabel('Region'))

        expect(await screen.findByText('General regions')).toBeInTheDocument()
        expect(screen.queryByText('Specific regions')).not.toBeInTheDocument()
      })

      test('the link reopens the dropdown on the full list with the general region still selected', async () => {
        mockWizardEndpoints({ organizations: FREE_PLAN_ORG })
        const onRequest = vi.fn()
        mockCreateProject(onRequest)

        await renderWizard()

        await fillProjectName('Specific Region Link Project')
        await generateAndWaitForStrongPassword()
        await selectRegion(/Americas/)

        await user.click(screen.getByRole('button', { name: 'Need a specific region?' }))

        expect(await screen.findByText('Specific regions')).toBeInTheDocument()
        expect(screen.getByText('General regions')).toBeInTheDocument()
        expect(getSelectTriggerByLabel('Region')).toHaveTextContent('Americas')

        await user.click(await findOption(/East US/))

        expect(
          screen.queryByRole('button', { name: 'Need a specific region?' })
        ).not.toBeInTheDocument()
        expect(await submitAndReadRegionSelection(onRequest)).toMatchObject({ code: 'us-east-1' })
      })

      test('does not apply to a paid-plan org: the full region list shows directly with no link', async () => {
        mockWizardEndpoints()

        await renderWizard()

        await screen.findByPlaceholderText('Project name')
        await user.click(getSelectTriggerByLabel('Region'))

        const recommendedOption = await findOption(/Americas/)
        expect(within(recommendedOption).getByText('Recommended')).toBeInTheDocument()
        expect(screen.getByText('General regions')).toBeInTheDocument()
        expect(screen.getByText('Specific regions')).toBeInTheDocument()
        expect(
          screen.queryByRole('button', { name: 'Need a specific region?' })
        ).not.toBeInTheDocument()
      })
    })

    test('blocks submission when available regions fail to load', async () => {
      mockWizardEndpoints({ availableRegions: 'error' })
      const onRequest = vi.fn()
      mockCreateProject(onRequest)

      await renderWizard()

      await screen.findByText('Error loading available regions')
      await fillProjectName('Unavailable Regions Project')
      await generateAndWaitForStrongPassword()

      const submitButton = screen.getByRole('button', { name: 'Create new project' })
      expect(submitButton).toBeDisabled()
      const form = submitButton.closest('form')
      if (!form) throw new Error('Project creation form not found')
      await act(async () => {
        fireEvent.submit(form)
      })
      expect(onRequest).not.toHaveBeenCalled()
    })

    test('blocks a previously selected region when regions fail to load for the new compute size', async () => {
      mockWizardEndpoints()
      const onRequest = vi.fn()
      mockCreateProject(onRequest)

      await renderWizard()

      await fillProjectName('Changed Compute Project')
      await generateAndWaitForStrongPassword()
      await selectRegion(/Americas/)

      addAPIMock({
        method: 'get',
        path: '/platform/projects/available-regions',
        response: () => HttpResponse.error(),
      })
      await user.click(getSelectTriggerByLabel('Compute size'))
      await user.click(await findOption(/2 GB RAM/))
      await screen.findByText('Error loading available regions')

      const submitButton = screen.getByRole('button', { name: 'Create new project' })
      expect(submitButton).toBeDisabled()
      const form = submitButton.closest('form')
      if (!form) throw new Error('Project creation form not found')
      await act(async () => {
        fireEvent.submit(form)
      })
      expect(onRequest).not.toHaveBeenCalled()
    })

    describe('free tier general region experiment', () => {
      test('keeps the region selector loading while flags are being re-evaluated', async () => {
        mockWizardEndpoints({
          organizations: [mockOrg({ plan: { id: 'free', name: 'Free' } })],
        })

        await renderWizard({
          flags: {
            freeTierGeneralRegionEnrollment: true,
            freeTierGeneralRegionSelection: true,
          },
          isConfigCatStale: true,
        })

        await screen.findByPlaceholderText('Project name')
        expect(await screen.findByText('Loading available regions...')).toBeInTheDocument()
        expect(getSelectTriggerByLabel('Region')).toBeDisabled()
      })

      test('restricts the picker to general regions with an upgrade footer for a free-plan org in the test arm', async () => {
        mockWizardEndpoints({
          organizations: [mockOrg({ plan: { id: 'free', name: 'Free' } })],
        })

        await renderWizard({
          flags: {
            freeTierGeneralRegionEnrollment: true,
            freeTierGeneralRegionSelection: true,
          },
        })

        await screen.findByPlaceholderText('Project name')
        await user.click(getSelectTriggerByLabel('Region'))

        expect(await screen.findByText('General regions')).toBeInTheDocument()
        expect(screen.queryByText('Specific regions')).not.toBeInTheDocument()
        expect(
          within(screen.getByRole('listbox')).queryByRole('option', { name: /North Virginia/ })
        ).not.toBeInTheDocument()

        const upgradeLink = screen.getByRole('link', { name: 'Upgrade to Pro' })
        expect(upgradeLink).toHaveAttribute(
          'href',
          `/org/${ORG_SLUG}/billing?panel=subscriptionPlan&source=freeTierGeneralRegionSelector`
        )

        expect(screen.getByRole('link', { name: 'specific region' })).toHaveAttribute(
          'href',
          expect.stringMatching(/\/guides\/platform\/regions$/)
        )
        // The upgrade footer replaces the "Need a specific region?" link
        expect(screen.queryByText('Need a specific region?')).not.toBeInTheDocument()
      })

      test('collapses specific regions behind the link for a free-plan org in the control arm', async () => {
        mockWizardEndpoints({
          organizations: [mockOrg({ plan: { id: 'free', name: 'Free' } })],
        })

        await renderWizard({
          flags: {
            freeTierGeneralRegionEnrollment: true,
            freeTierGeneralRegionSelection: false,
          },
        })

        await screen.findByPlaceholderText('Project name')
        await user.click(getSelectTriggerByLabel('Region'))

        expect(await screen.findByText('General regions')).toBeInTheDocument()
        expect(screen.queryByText('Specific regions')).not.toBeInTheDocument()
        expect(screen.queryByRole('link', { name: 'Upgrade to Pro' })).not.toBeInTheDocument()
        // The reveal button sits outside the open dropdown, so it is hidden from the a11y tree
        expect(screen.getByText('Need a specific region?')).toBeInTheDocument()
      })

      test('shows the full region picker with no upgrade footer for a paid-plan org even when enrolled', async () => {
        mockWizardEndpoints()

        await renderWizard({
          flags: {
            freeTierGeneralRegionEnrollment: true,
            freeTierGeneralRegionSelection: true,
          },
        })

        await screen.findByPlaceholderText('Project name')
        await user.click(getSelectTriggerByLabel('Region'))

        expect(await screen.findByText('Specific regions')).toBeInTheDocument()
        expect(screen.queryByRole('link', { name: 'Upgrade to Pro' })).not.toBeInTheDocument()
      })
    })

    describe('restricted regions', () => {
      const CAPACITY_COPY = {
        title: 'Selected region is at capacity',
        notice:
          'This region currently has capacity for Micro compute and above. Free plan projects run on Nano compute.',
      }
      const GENERIC_COPY = {
        title: 'Selected region is unavailable',
        notice: 'This region is temporarily unavailable for new projects.',
      }

      const expectSelectableRestrictedRegion = async (
        onRequest: ReturnType<typeof vi.fn>,
        copy: { title: string; notice: string }
      ) => {
        await fillProjectName('Restricted Region Project')
        await generateAndWaitForStrongPassword()
        await user.click(getSelectTriggerByLabel('Region'))

        const saoPaulo = await findOption(/São Paulo/)
        expect(saoPaulo).not.toHaveAttribute('aria-disabled', 'true')
        expect(within(saoPaulo).getByText('Unavailable')).toBeInTheDocument()
        expect(
          within(
            within(screen.getByRole('listbox')).getByRole('option', { name: /North Virginia/ })
          ).queryByText('Unavailable')
        ).not.toBeInTheDocument()
        await user.click(saoPaulo)

        expect(await screen.findByText(copy.title)).toBeInTheDocument()
        expect(screen.getByText(copy.notice, { exact: false })).toBeInTheDocument()

        fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

        const message = `${copy.title}. Select a different region to continue.`
        expect(await screen.findByText(message)).toBeInTheDocument()
        expect(onRequest).not.toHaveBeenCalled()

        await selectRegion(/Americas/)
        await waitFor(() => expect(screen.queryByText(message)).not.toBeInTheDocument())
        expect(screen.queryByText(copy.title)).not.toBeInTheDocument()
      }

      test.each<{
        scenario: string
        status: 'capacity' | 'other' | undefined
        flags: Record<string, boolean | string>
        copy: typeof GENERIC_COPY
      }>([
        {
          scenario: 'a capacity platform status',
          status: 'capacity' as const,
          flags: {},
          copy: CAPACITY_COPY,
        },
        {
          scenario: 'an "other" platform status (generic copy, not silently greyed out)',
          status: 'other' as const,
          flags: {},
          copy: GENERIC_COPY,
        },
        {
          scenario: 'a flag-only restriction with no platform status',
          status: undefined,
          flags: { projectCreationRestrictedRegions: '{"sa-east-1":"unavailable"}' },
          copy: GENERIC_COPY,
        },
      ])(
        'keeps the region selectable, explains it, and blocks submission for $scenario',
        async ({ status, flags, copy }) => {
          mockWizardEndpoints({ availableRegions: availableRegionsWithSaoPaulo(status) })
          const onRequest = vi.fn()
          mockCreateProject(onRequest)

          await renderWizard({ flags })

          await expectSelectableRestrictedRegion(onRequest, copy)
        }
      )
    })
  })

  describe('compute size and spend confirmation', () => {
    test('shows the compute costs confirmation modal for larger instance sizes', async () => {
      mockWizardEndpoints()
      const onRequest = vi.fn()
      mockCreateProject(onRequest)

      await renderWizard()

      await fillProjectName('Big Project')
      await generateAndWaitForStrongPassword()

      await user.click(getSelectTriggerByLabel('Compute size'))
      await user.click(await screen.findByText('4 GB RAM / Shared compute'))

      fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

      await screen.findByText('Confirm compute costs')
      expect(onRequest).not.toHaveBeenCalled()

      fireEvent.click(screen.getByRole('button', { name: 'I understand' }))

      await waitFor(() => expect(onRequest).toHaveBeenCalled())
      expect(onRequest.mock.calls[0][0].desired_instance_size).toBe('medium')
    })
  })

  describe('postgres version and orioledb', () => {
    test('hides advanced configuration when orioledb is unavailable', async () => {
      mockWizardEndpoints()
      const onAvailableVersionsRequest = vi.fn()
      addAPIMock({
        method: 'post',
        path: '/platform/organizations/:slug/available-versions',
        response: () => {
          onAvailableVersionsRequest()
          return HttpResponse.json<{ available_versions: AvailableVersion[] }>({
            available_versions: DEFAULT_AVAILABLE_VERSIONS.available_versions.slice(0, 1),
          })
        },
      })

      await renderWizard()

      await waitFor(() => expect(onAvailableVersionsRequest).toHaveBeenCalled())
      expect(
        screen.queryByRole('button', { name: 'Advanced Configuration' })
      ).not.toBeInTheDocument()
    })

    test('selecting orioledb shows the beta warning and submits the oriole engine/channel', async () => {
      mockWizardEndpoints()
      const onRequest = vi.fn()
      mockCreateProject(onRequest)

      await renderWizard()

      await fillProjectName('Oriole Project')
      await generateAndWaitForStrongPassword()
      await selectRegion(/Americas/)

      fireEvent.click(await screen.findByRole('button', { name: 'Advanced Configuration' }))
      await user.click(screen.getByRole('radio', { name: /Postgres with OrioleDB/ }))

      await screen.findByText('OrioleDB is not production ready')

      fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

      await waitFor(() => expect(onRequest).toHaveBeenCalled())
      const body = onRequest.mock.calls[0][0]
      expect(body.postgres_engine).toBe('17-oriole')
      expect(body.release_channel).toBe('beta')
    })

    test('hides advanced configuration only while high availability is enabled', async () => {
      mockWizardEndpoints()
      const onRequest = vi.fn()
      mockCreateProject(onRequest)

      await renderWizard()

      await fillProjectName('HA Oriole Project')
      await generateAndWaitForStrongPassword()
      await selectRegion(/Americas/)

      fireEvent.click(await screen.findByRole('button', { name: 'Advanced Configuration' }))
      await user.click(await screen.findByRole('radio', { name: /Postgres with OrioleDB/ }))

      const highAvailabilitySwitch = await screen.findByRole('switch')
      await user.click(highAvailabilitySwitch)

      expect(
        screen.queryByRole('button', { name: 'Advanced Configuration' })
      ).not.toBeInTheDocument()

      await user.click(highAvailabilitySwitch)
      expect(
        await screen.findByRole('button', { name: 'Advanced Configuration' })
      ).toBeInTheDocument()

      await user.click(highAvailabilitySwitch)
      fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))
      await waitFor(() => expect(onRequest).toHaveBeenCalled())
      expect(onRequest.mock.calls[0][0].postgres_engine).toBe('17')
      expect(onRequest.mock.calls[0][0].release_channel).toBe('ga')
    })

    test('keeps a manually selected Postgres version when available versions refetch', async () => {
      mockWizardEndpoints({ availableRegions: AVAILABLE_REGIONS_WITH_FRANKFURT })
      const onAvailableVersionsRequest = vi.fn()
      addAPIMock({
        method: 'post',
        path: '/platform/organizations/:slug/available-versions',
        response: () => {
          onAvailableVersionsRequest()
          return HttpResponse.json<{ available_versions: AvailableVersion[] }>(
            DEFAULT_AVAILABLE_VERSIONS
          )
        },
      })

      await renderWizard({ flags: { newProjectInternalOnlyConfiguration: true } })

      await fillProjectName('Sticky Version Project')
      await selectRegion(/Americas/)
      fireEvent.click(await screen.findByRole('button', { name: 'Internal-only Configuration' }))

      // Auto-selects the GA default once versions load
      await waitFor(() =>
        expect(screen.getByLabelText('Postgres version')).toHaveTextContent('15.6.1.139')
      )

      await user.click(screen.getByLabelText('Postgres version'))
      await user.click(await findOption(/17\.9\.9\.999/))
      expect(screen.getByLabelText('Postgres version')).toHaveTextContent('17.9.9.999')

      const requestsBeforeRegionChange = onAvailableVersionsRequest.mock.calls.length
      await selectRegion(/Frankfurt/)
      await waitFor(() =>
        expect(onAvailableVersionsRequest.mock.calls.length).toBeGreaterThan(
          requestsBeforeRegionChange
        )
      )

      expect(screen.getByLabelText('Postgres version')).toHaveTextContent('17.9.9.999')
    })

    test('keeps a non-default Postgres version when the internal panel is collapsed and reopened', async () => {
      mockWizardEndpoints()

      await renderWizard({ flags: { newProjectInternalOnlyConfiguration: true } })

      await screen.findByPlaceholderText('Project name')
      await selectRegion(/Americas/)
      const panelToggle = await screen.findByRole('button', {
        name: 'Internal-only Configuration',
      })
      fireEvent.click(panelToggle)

      await waitFor(() =>
        expect(screen.getByLabelText('Postgres version')).toHaveTextContent('15.6.1.139')
      )
      await user.click(screen.getByLabelText('Postgres version'))
      await user.click(await findOption(/17\.9\.9\.999/))
      expect(screen.getByLabelText('Postgres version')).toHaveTextContent('17.9.9.999')

      fireEvent.click(panelToggle)
      await waitFor(() => expect(screen.queryByLabelText('Postgres version')).toBeNull())
      fireEvent.click(panelToggle)

      await waitFor(() =>
        expect(screen.getByLabelText('Postgres version')).toHaveTextContent('17.9.9.999')
      )
    })

    test('blocks submission with a toast when orioledb becomes unavailable after selection', async () => {
      mockWizardEndpoints({ availableRegions: AVAILABLE_REGIONS_WITH_FRANKFURT })
      const onRequest = vi.fn()
      mockCreateProject(onRequest)

      await renderWizard()

      await fillProjectName('Oriole Gone Project')
      await generateAndWaitForStrongPassword()
      await selectRegion(/Americas/)

      fireEvent.click(await screen.findByRole('button', { name: 'Advanced Configuration' }))
      await user.click(screen.getByRole('radio', { name: /Postgres with OrioleDB/ }))
      await screen.findByText('OrioleDB is not production ready')

      addAPIMock({
        method: 'post',
        path: '/platform/organizations/:slug/available-versions',
        response: async ({ request }) => {
          const { region } = (await request.json()) as { region: string }
          return HttpResponse.json<{ available_versions: AvailableVersion[] }>(
            region === FRANKFURT
              ? { available_versions: DEFAULT_AVAILABLE_VERSIONS.available_versions.slice(0, 1) }
              : DEFAULT_AVAILABLE_VERSIONS
          )
        },
      })
      await selectRegion(/Frankfurt/)

      fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

      await waitFor(() =>
        expect(toast.error).toHaveBeenCalledWith(
          'No available OrioleDB image found, only Postgres is available'
        )
      )
      expect(onRequest).not.toHaveBeenCalled()
    })
  })

  describe('high availability', () => {
    test('shows the high availability toggle when the entitlement is enabled, and hides gated sections by default', async () => {
      mockWizardEndpoints()

      await renderWizard()

      expect(await screen.findByText('High availability')).toBeInTheDocument()
      expect(screen.getByText('Alpha')).toBeInTheDocument()
      expect(screen.getByText(/Free during Alpha for up to 2 projects/)).toBeInTheDocument()
      expect(
        screen
          .getByText('High availability')
          .compareDocumentPosition(screen.getByText('Compute size'))
      ).toBe(Node.DOCUMENT_POSITION_FOLLOWING)
      expect(
        screen.queryByRole('button', { name: 'Internal-only Configuration' })
      ).not.toBeInTheDocument()
      // No github_connections entitlement by default
      expect(screen.queryByText('GitHub (optional)')).not.toBeInTheDocument()
      expect(screen.queryByRole('button', { name: 'Connect GitHub' })).not.toBeInTheDocument()
    })

    test('hides the high availability toggle when the org lacks the entitlement', async () => {
      mockWizardEndpoints({
        entitlements: [
          {
            feature: { key: 'instances.high_availability', type: 'boolean' },
            hasAccess: false,
            type: 'boolean',
            config: { enabled: false },
          } as Entitlement,
        ],
      })

      await renderWizard()

      await screen.findByPlaceholderText('Project name')
      expect(screen.queryByText('High availability')).not.toBeInTheDocument()
    })

    test('removes the custom Postgres version field while high availability is enabled', async () => {
      mockWizardEndpoints()

      await renderWizard({
        flags: {
          newProjectInternalOnlyConfiguration: true,
        },
      })

      const highAvailabilitySwitch = await screen.findByRole('switch', {
        name: 'Enable high availability',
      })
      await user.click(highAvailabilitySwitch)
      fireEvent.click(await screen.findByRole('button', { name: 'Internal-only Configuration' }))

      expect(screen.getByLabelText('Postgres version')).toBeDisabled()
      expect(screen.queryByPlaceholderText('e.g 17.6.1.104')).not.toBeInTheDocument()

      await user.click(highAvailabilitySwitch)

      expect(await screen.findByPlaceholderText('e.g 17.6.1.104')).toBeInTheDocument()
    })

    test('shows high availability regions in a dedicated group', async () => {
      mockWizardEndpoints()

      await renderWizard()

      await user.click(await screen.findByRole('switch', { name: 'Enable high availability' }))
      await user.click(getSelectTriggerByLabel('Region'))

      expect(await screen.findByText('High Availability Regions')).toBeInTheDocument()
      expect(screen.queryByText('General regions')).not.toBeInTheDocument()
      expect(screen.queryByText('Specific regions')).not.toBeInTheDocument()
    })

    test('enabling high availability submits the fixed engine and AWS_K8S provider without a custom version', async () => {
      mockWizardEndpoints()
      const onRequest = vi.fn()
      mockCreateProject(onRequest)

      await renderWizard()

      await fillProjectName('HA Project')
      await generateAndWaitForStrongPassword()
      await user.click(await screen.findByRole('switch'))
      await selectRegion(/East US/)

      fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

      await waitFor(() => expect(onRequest).toHaveBeenCalled())
      const body = onRequest.mock.calls[0][0]
      expect(body.high_availability).toBe(true)
      expect(body.cloud_provider).toBe('AWS_K8S')
      expect(body.postgres_engine).toBe('17')
      expect(body.release_channel).toBe('ga')
      expect(body.custom_supabase_internal_requests).toBeUndefined()
    })

    // Regression (FE-4174): in local dev, region choice isn't restricted to the fixed HA
    // region (unlike staging), so a manual selection should be respected. onSubmit used to
    // resolve the HA region purely from highAvailabilityRegionCode without that same
    // exception, silently sending the fixed region regardless of what was displayed.
    test('submits the manually selected region in local dev instead of the fixed HA default', async () => {
      vi.stubEnv('NEXT_PUBLIC_ENVIRONMENT', 'local')
      try {
        mockWizardEndpoints({ availableRegions: AVAILABLE_REGIONS_WITH_FRANKFURT })
        const onRequest = vi.fn()
        mockCreateProject(onRequest)

        await renderWizard()

        await fillProjectName('Local HA Region Project')
        await generateAndWaitForStrongPassword()

        await user.click(await screen.findByRole('switch', { name: 'Enable high availability' }))
        // Local dev stacks aren't restricted to the fixed HA region, so the user can still
        // pick a different one from the (unrestricted) list.
        await selectRegion(/East US/)
        expect(getSelectTriggerByLabel('Region')).toHaveTextContent('East US (North Virginia)')

        fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

        await waitFor(() => expect(onRequest).toHaveBeenCalled())
        expect(onRequest.mock.calls[0][0].region_selection).toMatchObject({ code: 'us-east-1' })
      } finally {
        vi.unstubAllEnvs()
      }
    })

    test('forces the high availability region over a manually selected region and restores it', async () => {
      vi.stubEnv('NEXT_PUBLIC_ENVIRONMENT', 'staging')
      try {
        mockWizardEndpoints({ availableRegions: AVAILABLE_REGIONS_WITH_FRANKFURT })

        await renderWizard()

        await screen.findByPlaceholderText('Project name')
        await selectRegion(/Frankfurt/)
        expect(getSelectTriggerByLabel('Region')).toHaveTextContent(FRANKFURT)

        const highAvailabilitySwitch = await screen.findByRole('switch', {
          name: 'Enable high availability',
        })
        await user.click(highAvailabilitySwitch)

        await waitFor(() =>
          expect(getSelectTriggerByLabel('Region')).toHaveTextContent('East US (North Virginia)')
        )

        await user.click(highAvailabilitySwitch)

        await waitFor(() => expect(getSelectTriggerByLabel('Region')).toHaveTextContent(FRANKFURT))
      } finally {
        vi.unstubAllEnvs()
      }
    })

    test('restores the Postgres version selection when high availability is toggled off', async () => {
      mockWizardEndpoints()
      // Mirror staging: no versions offered for the standard provider, so the
      // selection only ever gets populated by the AWS_K8S list while HA is on.
      addAPIMock({
        method: 'post',
        path: '/platform/organizations/:slug/available-versions',
        response: async ({ request }) => {
          const { provider } = (await request.json()) as { provider: string }
          return HttpResponse.json<{ available_versions: AvailableVersion[] }>(
            provider === 'AWS_K8S' ? DEFAULT_AVAILABLE_VERSIONS : { available_versions: [] }
          )
        },
      })
      const onRequest = vi.fn()
      mockCreateProject(onRequest)

      await renderWizard({ flags: { newProjectInternalOnlyConfiguration: true } })

      await fillProjectName('HA Selection Restore Project')
      await generateAndWaitForStrongPassword()
      await selectRegion(/Americas/)
      fireEvent.click(await screen.findByRole('button', { name: 'Internal-only Configuration' }))

      const highAvailabilitySwitch = await screen.findByRole('switch', {
        name: 'Enable high availability',
      })
      await user.click(highAvailabilitySwitch)

      // The AWS_K8S versions load and auto-select a default while HA is on
      await waitFor(() =>
        expect(screen.getByLabelText('Postgres version')).toHaveTextContent('15.6.1.139')
      )

      await user.click(highAvailabilitySwitch)

      await waitFor(() =>
        expect(screen.getByLabelText('Postgres version')).toHaveTextContent(
          'Select a Postgres version for your project'
        )
      )

      fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

      await waitFor(() => expect(onRequest).toHaveBeenCalled())
      const body = onRequest.mock.calls[0][0]
      expect(body.high_availability).toBe(false)
      expect(body.cloud_provider).toBe('AWS')
      expect(body.postgres_engine).toBeUndefined()
      expect(body.release_channel).toBeUndefined()
      expect(body.custom_supabase_internal_requests).toBeUndefined()
    })

    test('restores a manually selected Postgres version selection after HA toggle', async () => {
      mockWizardEndpoints()
      addAPIMock({
        method: 'post',
        path: '/platform/organizations/:slug/available-versions',
        response: async ({ request }) => {
          const { provider } = (await request.json()) as { provider: string }
          return HttpResponse.json<{ available_versions: AvailableVersion[] }>(
            provider === 'AWS_K8S'
              ? { available_versions: DEFAULT_AVAILABLE_VERSIONS.available_versions.slice(0, 1) }
              : DEFAULT_AVAILABLE_VERSIONS
          )
        },
      })

      await renderWizard({ flags: { newProjectInternalOnlyConfiguration: true } })

      await fillProjectName('Manual Selection Restore Project')
      await selectRegion(/Americas/)
      fireEvent.click(await screen.findByRole('button', { name: 'Internal-only Configuration' }))

      await waitFor(() =>
        expect(screen.getByLabelText('Postgres version')).toHaveTextContent('15.6.1.139')
      )
      await user.click(screen.getByLabelText('Postgres version'))
      await user.click(await findOption(/17\.9\.9\.999/))
      expect(screen.getByLabelText('Postgres version')).toHaveTextContent('17.9.9.999')

      const highAvailabilitySwitch = await screen.findByRole('switch', {
        name: 'Enable high availability',
      })
      await user.click(highAvailabilitySwitch)
      await user.click(highAvailabilitySwitch)

      await waitFor(() =>
        expect(screen.getByLabelText('Postgres version')).toHaveTextContent('17.9.9.999')
      )
    })
  })

  describe('security options', () => {
    test('disabling the Data API sends an empty exposed-schemas list', async () => {
      mockWizardEndpoints()
      const onRequest = vi.fn()
      mockCreateProject(onRequest)

      await renderWizard()

      await fillProjectName('No Data API Project')
      await generateAndWaitForStrongPassword()

      await user.click(screen.getByLabelText('Enable Data API'))
      await screen.findByText('Client libraries need Data API to query your database')

      fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

      await waitFor(() => expect(onRequest).toHaveBeenCalled())
      const body = onRequest.mock.calls[0][0]
      expect(body.data_api_exposed_schemas).toEqual([])
      expect(body.data_api_revoke_default_privileges).toBe(false)
    })

    test('disabling default privileges sends the revoke flag', async () => {
      mockWizardEndpoints()
      const onRequest = vi.fn()
      mockCreateProject(onRequest)

      await renderWizard()

      await fillProjectName('Manual Privileges Project')
      await generateAndWaitForStrongPassword()

      await user.click(screen.getByLabelText('Automatically expose new tables'))

      fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

      await waitFor(() => expect(onRequest).toHaveBeenCalled())
      const body = onRequest.mock.calls[0][0]
      expect(body.data_api_exposed_schemas).toBeUndefined()
      expect(body.data_api_revoke_default_privileges).toBe(true)
    })

    test('enabling automatic RLS sends the event-trigger SQL', async () => {
      mockWizardEndpoints()
      const onRequest = vi.fn()
      mockCreateProject(onRequest)

      await renderWizard()

      await fillProjectName('Auto RLS Project')
      await generateAndWaitForStrongPassword()

      await user.click(screen.getByLabelText('Enable automatic RLS'))

      fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

      await waitFor(() => expect(onRequest).toHaveBeenCalled())
      expect(onRequest.mock.calls[0][0].db_sql).toBe(AUTO_ENABLE_RLS_EVENT_TRIGGER_SQL)
    })
  })

  test('blocks submission for a weak database password', async () => {
    mockWizardEndpoints()
    const onRequest = vi.fn()
    mockCreateProject(onRequest)

    await renderWizard()

    await fillProjectName('Weak Password Project')
    fireEvent.change(screen.getByPlaceholderText('Type in a strong password'), {
      target: { value: 'password' },
    })

    await waitFor(() =>
      expect(screen.getByRole('progressbar')).not.toHaveAttribute('aria-valuenow', '100')
    )

    fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

    await screen.findByText(/You need a stronger password\./)
    expect(onRequest).not.toHaveBeenCalled()
  })

  test('blocks submission for a too-short project name', async () => {
    mockWizardEndpoints()
    const onRequest = vi.fn()
    mockCreateProject(onRequest)

    await renderWizard()

    await fillProjectName('ab')
    await generateAndWaitForStrongPassword()

    fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

    await screen.findByText('Project name must be at least 3 characters long.')
    expect(onRequest).not.toHaveBeenCalled()
  })

  describe('github integration', () => {
    test('selecting a connected repository fills in the project name and submission payload', async () => {
      mockWizardEndpoints({
        entitlements: [
          {
            feature: { key: 'integrations.github_connections', type: 'boolean' },
            hasAccess: true,
            type: 'boolean',
            config: { enabled: true },
          } as Entitlement,
        ],
        githubAuthorization: { id: 1 },
        githubRepositories: {
          partial_response_due_to_sso: false,
          repositories: [
            { id: 555, installation_id: 777, name: 'my-org/my-repo', default_branch: 'main' },
          ],
        },
      })
      const onRequest = vi.fn()
      mockCreateProject(onRequest)

      await renderWizard()

      await screen.findByPlaceholderText('Project name')
      fireEvent.click(await screen.findByText('Choose GitHub repository'))
      await user.click(await screen.findByText('my-org/my-repo'))

      await waitFor(() =>
        expect(screen.getByPlaceholderText('Project name')).toHaveValue('my-repo')
      )

      await generateAndWaitForStrongPassword()
      fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

      await waitFor(() => expect(onRequest).toHaveBeenCalled())
      const body = onRequest.mock.calls[0][0]
      expect(body.github_repository_id).toBe(555)
      expect(body.github_installation_id).toBe(777)
    })
  })

  test('shows an error toast when project creation fails', async () => {
    mockWizardEndpoints()
    addAPIMock({
      method: 'post',
      path: '/platform/projects',
      response: () =>
        HttpResponse.json<APIErrorBody>({ message: 'Organization is over quota' }, { status: 400 }),
    })

    await renderWizard()

    await fillProjectName('Failing Project')
    await generateAndWaitForStrongPassword()
    fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))

    await waitFor(() =>
      expect(toast.error).toHaveBeenCalledWith(
        expect.stringContaining('Organization is over quota')
      )
    )
  })
})