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

import { getAllByRole, waitFor } from '@testing-library/vue'

import { getByIconName } from '#tests/support/components/iconQueries.ts'
import { renderComponent } from '#tests/support/components/index.ts'
import { mockApplicationConfig } from '#tests/support/mock-applicationConfig.ts'
import { mockGraphQLApi } from '#tests/support/mock-graphql-api.ts'
import { nullableMock } from '#tests/support/utils.ts'

import { ObjectManagerFrontendAttributesDocument } from '#shared/entities/core/attributes/graphql/queries/objectManagerFrontendAttributes.api.ts'
import type { TicketArticle } from '#shared/entities/ticket/types.ts'
import { EnumSecurityStateType } from '#shared/graphql/types.ts'
import type { DeepPartial } from '#shared/types/utils.ts'

import { ticketArticleObjectAttributes } from '#mobile/entities/ticket/__tests__/mocks/ticket-mocks.ts'
import { defaultArticles } from '#mobile/pages/ticket/__tests__/mocks/detail-view.ts'

import ArticleMetadataDialog from '../ArticleMetadataDialog.vue'

// parsed is tested in unit test
const getAddress = (raw: string) => ({
  __typename: 'AddressesField' as const,
  raw,
  parsed: null,
})

describe('visuals for metadata', () => {
  it('renders article metadata', async () => {
    mockGraphQLApi(ObjectManagerFrontendAttributesDocument).willBehave(() => {
      return {
        data: {
          objectManagerFrontendAttributes: ticketArticleObjectAttributes(),
        },
      }
    })

    const createdAt = new Date(2022, 1, 1, 0, 0, 0, 0).toISOString()

    const article: TicketArticle = {
      // default article has attachment that should be visible as a link
      ...defaultArticles().firstArticles!.edges[0].node,
      internalId: 1,
      from: getAddress('"Test Admin Agent via Zammad Helpdesk" <zammad@localhost>'),
      to: getAddress('Nicole Braun <nicole.braun@zammad.org>'),
      subject: 'Some Email',
      cc: getAddress('Joe Mike <joe.mike@zammad.org>'),
      replyTo: getAddress('Arthur Miller <arthur.miller@zammad.org>'),
      type: {
        __typename: 'TicketArticleType',
        name: 'email',
        communication: true,
      },
      detectedLanguage: 'de',
      createdAt,
      preferences: {
        links: [
          {
            name: 'Facebook',
            url: 'https://www.facebook.com/zammad',
            target: '_blank',
          },
        ],
      },
    }

    const view = renderComponent(ArticleMetadataDialog, {
      props: {
        name: 'article',
        article,
        ticketInternalId: 2,
        isTicketAgent: true,
      },
      router: true,
      store: true,
    })

    expect(view.getByRole('region', { name: 'From' })).toHaveTextContent(
      /Test Admin Agent via Zammad Helpdesk/,
    )
    expect(view.getByRole('region', { name: 'To' })).toHaveTextContent(
      /Nicole Braun <nicole.braun@zammad.org>/,
    )
    expect(view.getByRole('region', { name: 'Subject' })).toHaveTextContent(/Some Email/)
    expect(view.getByRole('region', { name: 'CC' })).toHaveTextContent(
      /Joe Mike <joe.mike@zammad.org>/,
    )
    expect(view.getByRole('region', { name: 'Reply-To' })).toHaveTextContent(
      /Arthur Miller <arthur.miller@zammad.org/,
    )
    expect(view.getByRole('region', { name: 'Created' })).toHaveTextContent(/2022-02-01 00:00$/)

    // FIXME: The content does not get replaced with the associated option,
    //   even though the correct object attribute is loaded.
    await waitFor(() => {
      expect(view.getByRole('region', { name: 'Detected language' })).toHaveTextContent(/German$/)
    })

    const channel = view.getByRole('region', { name: 'Channel' })
    expect(channel).toHaveTextContent(/email/)
    expect(view.getByIconName('mail')).toBeInTheDocument()
    const links = getAllByRole(channel, 'link')
    expect(links).toHaveLength(3)

    const [facebook, raw, attachment] = links

    expect(facebook).toHaveTextContent('Facebook')
    expect(facebook).toHaveAttribute('href', 'https://www.facebook.com/zammad')

    expect(raw).toHaveTextContent('Raw')
    expect(raw).toHaveAttribute('href', '/api/ticket_article_plain/1')

    expect(attachment).toHaveTextContent('Original formatting')
    expect(attachment).toHaveAttribute(
      'href',
      '/api/ticket_attachment/2/1/66?disposition=attachment',
    )

    expect(view.queryByRole('region', { name: 'Security' })).not.toBeInTheDocument()
  })

  it('does not render the detected language in the customer view', () => {
    const view = renderComponent(ArticleMetadataDialog, {
      props: {
        name: 'article',
        article: nullableMock<TicketArticle>({
          ...defaultArticles().firstArticles!.edges[0].node,
          detectedLanguage: 'de',
        }),
        ticketInternalId: 2,
        isTicketAgent: false,
      },
      router: true,
      store: true,
    })

    expect(view.queryByRole('region', { name: 'Detected language' })).not.toBeInTheDocument()
  })
})

describe('rendering security field', () => {
  const mockArticle = (
    security: DeepPartial<NonNullable<TicketArticle['securityState']>>,
  ): TicketArticle =>
    nullableMock<TicketArticle>({
      ...defaultArticles().firstArticles!.edges[0].node,
      internalId: 1,
      securityState: {
        __typename: 'TicketArticleSecurityState',
        ...security,
      },
    })

  describe('renders type', () => {
    it('renders S/MIME type when provided', () => {
      const view = renderComponent(ArticleMetadataDialog, {
        props: {
          name: 'article',
          article: mockArticle({
            encryptionMessage: '',
            encryptionSuccess: true,
            signingMessage: '',
            signingSuccess: true,
            type: EnumSecurityStateType.Smime,
          }),
          ticketInternalId: 2,
        },
        router: true,
        store: true,
      })

      const security = view.getByRole('region', { name: 'Security' })
      expect(security).toHaveTextContent('S/MIME')
    })

    it('renders PGP type when provided', () => {
      const view = renderComponent(ArticleMetadataDialog, {
        props: {
          name: 'article',
          article: mockArticle({
            encryptionMessage: '',
            encryptionSuccess: true,
            signingMessage: '',
            signingSuccess: true,
            type: EnumSecurityStateType.Pgp,
          }),
          ticketInternalId: 2,
        },
        router: true,
        store: true,
      })

      const security = view.getByRole('region', { name: 'Security' })
      expect(security).toHaveTextContent('PGP')
    })
  })

  describe('renders encryption', () => {
    const mockEncryption = (success: boolean, comment: string) =>
      mockArticle({ encryptionSuccess: success, encryptionMessage: comment })
    const renderEncryption = (success: boolean, comment: string) => {
      return renderComponent(ArticleMetadataDialog, {
        props: {
          name: 'article',
          article: mockEncryption(success, comment),
          ticketInternalId: 2,
        },
        router: true,
        store: true,
      })
    }

    it('renders successful encryption, if provided', () => {
      const view = renderEncryption(true, '')

      const security = view.getByRole('region', { name: 'Security' })
      expect(security).toHaveTextContent('Encrypted')
      expect(getByIconName(security, 'lock')).toBeInTheDocument()
    })

    it('renders unsuccessful encryption, if provided', () => {
      const view = renderEncryption(false, 'Private key could not be found.')

      const security = view.getByRole('region', { name: 'Security' })
      expect(security).toHaveTextContent('Encryption error Private key could not be found.')
      expect(getByIconName(security, 'encryption-error')).toBeInTheDocument()
    })
  })

  describe('renders sign', () => {
    const mockSign = (success: boolean, comment: string) =>
      mockArticle({ signingSuccess: success, signingMessage: comment })
    const renderSign = (success: boolean, comment: string) => {
      return renderComponent(ArticleMetadataDialog, {
        props: {
          name: 'article',
          article: mockSign(success, comment),
          ticketInternalId: 2,
        },
        router: true,
        store: true,
      })
    }

    it('renders successful signature, if provided', () => {
      const view = renderSign(true, '')

      const security = view.getByRole('region', { name: 'Security' })
      expect(security).toHaveTextContent('Signed')
      expect(getByIconName(security, 'signed')).toBeInTheDocument()
    })

    it('renders unsuccessful signature, if provided', () => {
      const view = renderSign(false, 'Public key could not be found.')

      const security = view.getByRole('region', { name: 'Security' })
      expect(security).toHaveTextContent('Sign error Public key could not be found.')
      expect(getByIconName(security, 'not-signed')).toBeInTheDocument()
    })
  })

  it('renders both, if provided', () => {
    const article = mockArticle({
      encryptionMessage: '',
      signingMessage: '',
      signingSuccess: true,
      encryptionSuccess: true,
    })

    const view = renderComponent(ArticleMetadataDialog, {
      props: {
        name: 'article',
        article,
        ticketInternalId: 2,
      },
      router: true,
      store: true,
    })

    const security = view.getByRole('region', { name: 'Security' })
    expect(security).toHaveTextContent('Encrypted Signed')
    expect(getByIconName(security, 'lock')).toBeInTheDocument()
    expect(getByIconName(security, 'signed')).toBeInTheDocument()
  })
})

describe('rendering WhatsApp metadata', () => {
  const mockArticle = (whatsappPreferences: object): TicketArticle => ({
    ...defaultArticles().firstArticles!.edges[0].node,
    internalId: 1,
    preferences: {
      whatsapp: whatsappPreferences,
    },
  })

  describe('renders message status', () => {
    it('renders correct icon + text for "sent"', () => {
      const view = renderComponent(ArticleMetadataDialog, {
        props: {
          name: 'article',
          article: mockArticle({
            timestamp_sent: new Date(2022, 1, 1, 0, 0, 0, 0).toISOString(),
          }),
          ticketInternalId: 2,
        },
        router: true,
        store: true,
      })

      const messageStatus = view.getByRole('region', { name: 'Message status' })
      expect(messageStatus).toHaveTextContent('sent to the customer')
      expect(getByIconName(messageStatus, 'check')).toBeInTheDocument()
    })

    it('renders correct icon + text for "delivered"', () => {
      const view = renderComponent(ArticleMetadataDialog, {
        props: {
          name: 'article',
          article: mockArticle({
            timestamp_sent: new Date(2022, 1, 1, 0, 0, 0, 0).toISOString(),
            timestamp_delivered: new Date(2022, 1, 1, 0, 0, 0, 0).toISOString(),
          }),
          ticketInternalId: 2,
        },
        router: true,
        store: true,
      })

      const messageStatus = view.getByRole('region', { name: 'Message status' })
      expect(messageStatus).toHaveTextContent('delivered to the customer')
      expect(getByIconName(messageStatus, 'check-double')).toBeInTheDocument()
    })

    it('renders correct icon + text for "read"', () => {
      const view = renderComponent(ArticleMetadataDialog, {
        props: {
          name: 'article',
          article: mockArticle({
            timestamp_sent: new Date(2022, 1, 1, 0, 0, 0, 0).toISOString(),
            timestamp_delivered: new Date(2022, 1, 1, 0, 0, 0, 0).toISOString(),
            timestamp_read: new Date(2022, 1, 1, 0, 0, 0, 0).toISOString(),
          }),
          ticketInternalId: 2,
        },
        router: true,
        store: true,
      })

      const messageStatus = view.getByRole('region', { name: 'Message status' })
      expect(messageStatus).toHaveTextContent('read by the customer')
      expect(getByIconName(messageStatus, 'check-double-circle')).toBeInTheDocument()
    })
  })
})

describe('rendering accounted time', () => {
  const mockArticle = (
    timeUnit: TicketArticle['timeUnit'],
    accountedTimeType?: string,
  ): TicketArticle =>
    nullableMock<TicketArticle>({
      ...defaultArticles().firstArticles!.edges[0].node,
      internalId: 1,
      timeUnit,
      accountedTimeType: accountedTimeType
        ? { __typename: 'TicketTimeAccountingType', name: accountedTimeType }
        : null,
    })

  const renderDialog = (timeUnit: TicketArticle['timeUnit'], accountedTimeType?: string) =>
    renderComponent(ArticleMetadataDialog, {
      props: {
        name: 'article',
        article: mockArticle(timeUnit, accountedTimeType),
        ticketInternalId: 2,
      },
      router: true,
      store: true,
    })

  it('renders the accounted time with the configured unit', () => {
    mockApplicationConfig({ time_accounting_unit: 'minute' })

    const view = renderDialog(5)

    expect(view.getByRole('region', { name: 'Accounted time' })).toHaveTextContent('5.00 minute(s)')
  })

  it('renders the accounted time alone when no unit is configured', () => {
    mockApplicationConfig({ time_accounting_unit: '' })

    const view = renderDialog(1.5)

    expect(view.getByRole('region', { name: 'Accounted time' })).toHaveTextContent(/1\.50$/)
  })

  it('does not render the accounted time when there is none', () => {
    const view = renderDialog(null)

    expect(view.queryByRole('region', { name: 'Accounted time' })).not.toBeInTheDocument()
  })

  it('renders the activity type together with the accounted time', () => {
    mockApplicationConfig({ time_accounting_unit: 'minute', time_accounting_types: true })

    const view = renderDialog(5, 'Billing')

    const accountedTime = view.getByRole('region', { name: 'Accounted time' })

    expect(accountedTime).toHaveTextContent('5.00 minute(s)')
    expect(accountedTime).toHaveTextContent('for activity type')
    expect(accountedTime).toHaveTextContent('Billing')
  })

  it('does not render the activity type when the feature is disabled', () => {
    mockApplicationConfig({ time_accounting_unit: 'minute', time_accounting_types: false })

    const view = renderDialog(5, 'Billing')

    expect(view.getByRole('region', { name: 'Accounted time' })).toHaveTextContent(
      /5\.00 minute\(s\)$/,
    )
  })

  it('does not render the activity type when there is none', () => {
    mockApplicationConfig({ time_accounting_unit: 'minute', time_accounting_types: true })

    const view = renderDialog(5)

    expect(view.getByRole('region', { name: 'Accounted time' })).toHaveTextContent(
      /5\.00 minute\(s\)$/,
    )
  })
})
