// Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/

import { effectScope } from 'vue'

import { visitView } from '#tests/support/components/visitView.ts'
import { mockApplicationConfig } from '#tests/support/mock-applicationConfig.ts'
import { mockGraphQLApi } from '#tests/support/mock-graphql-api.ts'

import { useNotifications } from '#shared/components/CommonNotifications/index.ts'
import { useUnknownAddressDetection } from '#shared/composables/useUnknownAddressDetection.ts'
import {
  mockPublicLinks,
  mockPublicLinksSubscription,
} from '#shared/entities/public-links/__tests__/mocks/mockPublicLinks.ts'
import { LoginDocument } from '#shared/graphql/mutations/login.api.ts'
import { EnumTwoFactorAuthenticationMethod } from '#shared/graphql/types.ts'

describe('testing login error handling', () => {
  beforeEach(() => {
    mockPublicLinks([])
    mockPublicLinksSubscription()
    mockApplicationConfig({ product_name: 'Zammad' })
  })

  it('check required login fields', async () => {
    const view = await visitView('/login')
    await view.events.click(view.getByText('Sign in'))

    expect(view.getByLabelText('Username / Email')).toBeDescribedBy('This field is required.')

    expect(view.getByLabelText('Password')).toBeDescribedBy('This field is required.')
  })

  it('check that login request error is visible', async () => {
    mockGraphQLApi(LoginDocument).willFailWithUserError({
      login: {
        session: null,
        errors: [
          {
            message:
              'Login failed. Have you double-checked your credentials and completed the email verification step?',
          },
        ],
        twoFactorRequired: null,
      },
    })

    const view = await visitView('/login')

    const loginInput = view.getByPlaceholderText('Username / Email')
    const passwordInput = view.getByPlaceholderText('Password')

    await view.events.type(loginInput, 'admin@example.com')
    await view.events.type(passwordInput, 'wrong')

    await view.events.click(view.getByText('Sign in'))

    expect(view.getByTestId('notification')).toBeInTheDocument()
    expect(view.getByTestId('notification')).toHaveTextContent(
      'Login failed. Have you double-checked your credentials and completed the email verification step?',
    )
  })

  it('check that two factor request error is visible', async () => {
    mockGraphQLApi(LoginDocument).willResolve([
      {
        login: {
          session: null,
          errors: null,
          twoFactorRequired: {
            availableTwoFactorAuthenticationMethods: [
              EnumTwoFactorAuthenticationMethod.AuthenticatorApp,
            ],
            defaultTwoFactorAuthenticationMethod:
              EnumTwoFactorAuthenticationMethod.AuthenticatorApp,
            recoveryCodesAvailable: false,
          },
        },
      },
      {
        login: {
          session: null,
          errors: [
            {
              __typename: 'UserError',
              message: 'Login failed. Please double-check your two-factor authentication method.',
              field: null,
              messagePlaceholder: null,
              exception: null,
            },
          ],
          twoFactorRequired: null,
        },
      },
    ])

    const view = await visitView('/login')

    const loginInput = view.getByPlaceholderText('Username / Email')
    const passwordInput = view.getByPlaceholderText('Password')

    await view.events.type(loginInput, 'admin@example.com')
    await view.events.type(passwordInput, 'wrong')

    await view.events.click(view.getByText('Sign in'))

    await view.events.type(view.getByLabelText('Security code'), '123456')

    await view.events.click(view.getByText('Sign in'))

    expect(view.getByTestId('notification')).toBeInTheDocument()
    expect(view.getByTestId('notification')).toHaveTextContent(
      'Login failed. Please double-check your two-factor authentication method.',
    )
  })

  it('keeps the unknown address warning when the login fails', async () => {
    mockApplicationConfig({ fqdn: 'zammad.org', http_type: 'https' })

    const scope = effectScope()
    scope.run(() => useUnknownAddressDetection())

    onTestFinished(() => {
      scope.stop()
      useNotifications().removeNotification('unknown-fqdn-redirect')
    })

    mockGraphQLApi(LoginDocument).willFailWithUserError({
      login: {
        session: null,
        errors: [{ message: 'Login failed.' }],
        twoFactorRequired: null,
      },
    })

    const view = await visitView('/login')

    await view.events.type(view.getByPlaceholderText('Username / Email'), 'admin@example.com')
    await view.events.type(view.getByPlaceholderText('Password'), 'wrong')

    await view.events.click(view.getByText('Sign in'))

    const notifications = view.getAllByTestId('notification')

    expect(notifications).toHaveLength(2)
    expect(notifications[0]).toHaveTextContent("This isn't the address Zammad is set up for.")
    expect(notifications[1]).toHaveTextContent('Login failed.')
  })
})
