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

require 'rails_helper'

require 'system/examples/text_modules_examples'

RSpec.describe 'User Profile', type: :system do
  let(:organizations) { create_list(:organization, 20) }
  let(:customer)      { create(:customer, organization: organizations[0], organizations: organizations[1..]) }

  it 'does show the edit link' do
    visit "#user/profile/#{customer.id}"
    click '#userAction label'
    click_on 'Edit'
    modal_ready
  end

  describe 'object manager attributes maxlength', authenticated_as: :authenticate, db_strategy: :reset do
    def authenticate
      customer
      create(:object_manager_attribute_text, :required_screen, object_name: 'User', name: 'maxtest', display: 'maxtest', data_option: {
               'type'      => 'text',
               'maxlength' => 3,
               'null'      => true,
               'translate' => false,
               'default'   => '',
               'options'   => {},
               'relation'  => '',
             })
      ObjectManager::Attribute.migration_execute
      true
    end

    it 'limits the input to the maximum length' do
      visit "#user/profile/#{customer.id}"
      within(:active_content) do
        page.find('.profile .js-action').click
        page.find('.profile li[data-type=edit]').click
        fill_in 'maxtest', with: 'hellu'
        expect(page).to have_field('maxtest', with: 'hel')
      end
    end
  end

  it 'check that ignored attributes for user popover are not visible' do
    visit '/'

    fill_in id: 'global-search', with: customer.email

    popover_on_hover(find('.nav-tab--search.user'))

    expect(page).to have_css('.popover label', count: 2)
  end

  context 'when calling without session' do
    describe 'redirect to' do
      it 'login screen', authenticated_as: false do
        visit "#user/profile/#{customer.id}"

        expect(page).to have_css('#login')
      end
    end
  end

  context 'Assign user to multiple organizations #1573', authenticated_as: :authenticate do
    def authenticate
      customer
      true
    end

    before do
      visit "#user/profile/#{customer.id}"
    end

    it 'shows only first 3 organizations and loads more on demand' do
      # The secondary organization ids come without a defined order, only their number is stable.
      shown_organizations = '.js-organizationList li:not(.js-showMoreOrganizations)'

      within :active_content do
        expect(page).to have_css(shown_organizations, count: 3)

        click '.js-showMoreOrganizations a'

        expect(page).to have_css(shown_organizations, count: organizations.size - 1)
      end
    end
  end

  context 'when ticket changes in user profile', authenticated_as: :authenticate do
    let(:ticket) { create(:ticket, title: SecureRandom.uuid, customer: create(:customer, :with_org), group: Group.first) }

    def authenticate
      ticket
      true
    end

    before do
      visit "#user/profile/#{ticket.customer.id}"
    end

    it 'does update when ticket changes' do
      expect(page).to have_text(ticket.title)
      wait_for_authenticated_session
      ticket.update(title: SecureRandom.uuid)
      expect(page).to have_text(ticket.title)
    end
  end

  describe 'Missing secondary organizations in user profile after refreshing with many secondary organizations. #4331' do
    before do
      visit "#user/profile/#{customer.id}"
      page.find('.profile .js-action').click
      page.find('.profile li[data-type=edit]').click
    end

    it 'does show all secondary organizations on edit' do
      # Secondary organizations are fetched via an async request (see
      # User#secondaryOrganizations) and the token list is (re-)rendered once
      # that resolves, so wait for it to settle instead of taking an instant
      # snapshot with #all, which can catch a partially rendered token list.
      expect(page).to have_css('div[data-attribute-name="organization_ids"] .token', count: 19)
    end
  end

  context 'with vip attribute' do
    it 'shows no crown icon if user is not vip' do
      user = create(:user)

      visit "#user/profile/#{user.id}"

      within '.profile-window' do
        expect(page).to have_no_css('.icon-crown')
      end
    end

    it 'shows the crown icon if user is vip' do
      user = create(:user, vip: true)

      visit "#user/profile/#{user.id}"

      within '.profile-window' do
        expect(page).to have_css('.icon-crown')
      end
    end
  end

  context 'with organization popover' do
    let(:organizations) do
      organization = create(:organization, vip: true)

      [organization]
    end

    it 'shows the organization popover' do
      visit "#user/profile/#{customer.id}"

      page.find('.profile-organization .organization-popover').hover

      within '.popover' do
        expect(page).to have_text(organizations[0].name, wait: 30)

        within '.avatar--organization' do
          expect(page).to have_css('.icon-crown-silver')
        end
      end
    end
  end

  describe 'resend verification email action' do
    let(:customer) { create(:customer, source: 'signup', verified: false, active: active) }

    before do
      visit "#user/profile/#{customer.id}"
      page.find('.profile .js-action').click
    end

    context 'with an active user' do
      let(:active) { true }

      it 'sends the verification email' do
        expect(page).to have_css('.profile li[data-type=resend_verification_email]:not([disabled])')

        page.find('.profile li[data-type=resend_verification_email]').click

        expect(page).to have_css('#notify .noty_message', text: %r{Email sent to .*#{Regexp.escape(customer.email)}}, visible: :all)
      end
    end

    context 'with an inactive user' do
      let(:active) { false }

      it 'shows the action as unavailable and sends no email' do
        expect(page)
          .to have_css('.profile li[data-type=resend_verification_email][disabled] a[aria-disabled=true]')
          .and have_css('.profile li[data-type=resend_verification_email] a[title="You cannot resend the verification email to an inactive user. Activate them first."]')

        page.find('.profile li[data-type=resend_verification_email]').click
        await_empty_ajax_queue

        expect(page).to have_no_css('#notify .noty_message', visible: :all)
      end
    end
  end
end
