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

require 'rails_helper'

RSpec.describe 'Desktop > Ticket > Edit', app: :desktop_view, authenticated_as: :agent, type: :system do
  let(:agent)   { create(:agent, password: 'test', groups: [group]) }
  let(:group)   { create(:group) }
  let(:article) { create(:ticket_article, :inbound_email, ticket: ticket) }
  let(:ticket)  { create(:ticket, group:, title: 'Test initial') }

  context 'when setting a pending reminder' do
    let(:pending_time) { 1.day.from_now.change(hour: 14, min: 37).beginning_of_minute }

    before do
      article

      visit "/ticket/#{ticket.id}"
      wait_for_form_to_settle("form-ticket-edit-#{ticket.id}")
    end

    def expect_pending_time_saved
      click_on 'Update'

      wait_for_gql('shared/entities/ticket/graphql/mutations/update.graphql', number: 1)

      expect(page).to have_text('Ticket updated successfully')
      expect(ticket.reload).to have_attributes(state: have_attributes(name: 'pending reminder'), pending_time: pending_time)
    end

    it 'saves a picked pending time' do
      within_form(form_updater_gql_number: 1) do
        find_select('State').select_option('pending reminder')
        find_datepicker('Pending till').select_datetime(pending_time)
      end

      expect(find_datepicker('Pending till')).to have_datetime(pending_time)

      expect_pending_time_saved
    end

    it 'saves a typed pending time' do
      within_form(form_updater_gql_number: 1) do
        find_select('State').select_option('pending reminder')
        find_datepicker('Pending till').type_datetime(pending_time)
      end

      expect(find_datepicker('Pending till')).to have_datetime(pending_time)

      expect_pending_time_saved
    end
  end

  context 'when editing a ticket', db_strategy: :reset do
    let(:select_field) { create(:object_manager_attribute_select, :shown_screen, name: 'select_field', display: 'Select field', additional_data_options: { options: { '1' => 'Option 1', '2' => 'Option 2', '3' => 'Option 3' } }) }
    let(:text_field)   { create(:object_manager_attribute_text, :shown_screen, name: 'text_field', display: 'Text field') }

    let(:hide_field_in_create) do
      create(:core_workflow,
             :active_and_screen,
             object:  'Ticket',
             screen:  'create_middle',
             perform: {
               'ticket.select_field': {
                 operator: 'hide',
                 hide:     true
               },
             })
    end

    let(:show_field_in_edit) do
      create(:core_workflow,
             :active_and_screen,
             object:  'Ticket',
             screen:  'edit',
             perform: {
               'ticket.select_field': {
                 operator:      'set_mandatory',
                 set_mandatory: true
               },
             })
    end

    before do
      select_field
      text_field
      ObjectManager::Attribute.migration_execute
      hide_field_in_create
      show_field_in_edit
      article

      visit "/ticket/#{ticket.id}"
      wait_for_form_to_settle("form-ticket-edit-#{ticket.id}")
    end

    it 'works correctly' do

      #
      # Ticket attributes
      #
      within_form(form_updater_gql_number: 1) do
        find_input('Text field').type('text content')

        click_on 'Update'

        # Check that select field is mandatory.
        expect(page).to have_text('This field is required.')

        find_select('Select field').select_option('Option 2')
      end

      click_on 'Update'

      wait_for_gql('shared/entities/ticket/graphql/mutations/update.graphql', number: 1)

      expect(page).to have_text('Ticket updated successfully')
      expect(ticket.reload).to have_attributes(select_field: '2', text_field: 'text content')

      #
      # Tag
      #
      click_on 'Add tag'
      find_autocomplete('Add tag').open.input_element.fill_in(with: 'test_tag').send_keys(:tab)
      wait_for_gql('shared/entities/tags/graphql/mutations/assignment/add.graphql', number: 1)
      expect(page).to have_text('Ticket tag added successfully')
      expect(ticket.tag_list).to include('test_tag')

      #
      # Title
      #
      within '[data-test-id="ticket-detail-top-bar-full-details"]' do
        find('[aria-label="Edit ticket title"]').click
      end
      # CommonInlineEdit focuses its field asynchronously (nextTick + queued
      #   task), and page-level keystrokes go to whatever is focused - typing
      #   after the save button renders but before the focus lands loses the
      #   leading keys (produced titles like 'Test initialed' in CI).
      expect(page).to have_css('[data-test-id="ticket-detail-top-bar-full-details"] textarea:focus')
      send_keys ' changed', :enter
      wait_for_gql('shared/entities/ticket/graphql/mutations/titleUpdate.graphql', number: 1)
      expect(page).to have_text('Ticket updated successfully')

      within 'main' do
        expect(page).to have_text('Test initial changed')
      end

      within '#user-taskbar-tabs' do
        expect(page).to have_text('Test initial changed')
      end

      #
      # State
      #
      find_select('State').select_option('closed')

      click_on 'Update'

      wait_for_gql('shared/entities/ticket/graphql/mutations/update.graphql', number: 2)

      expect(page).to have_text('Ticket updated successfully')
      expect(ticket.reload.state.name).to eq('closed')

      within '#user-taskbar-tabs' do
        expect(page).to have_css("a[href=\"/desktop/tickets/#{ticket.id}\"] svg[aria-label=\"closed\"]")
      end

      #
      # Reorder taskbar
      #
      click_on 'New ticket'
      expect(page).to have_css('label', text: 'Text field')
      expect(page).to have_no_css('label', text: 'Select field')

      within '#user-taskbar-tabs' do
        expect(page).to have_text("Test initial changed\nReceived call")

        o1 = find('li.draggable', text: 'Test initial changed')
        o2 = find('li.draggable', text: 'Received call')

        # Move the focus into the dragged tab before the drag: @formkit/drag-and-drop
        #  turns off the item's `draggable` attribute when focus enters it during
        #  a mouse press (handleNodeFocus), which would derail Capybara's HTML5
        #  drag emulation right at its initial press. With the focus already on
        #  the link, that press triggers no focus change and `draggable` stays on.
        #  #send_keys moves the focus without any pointer interaction - the lone
        #  shift key is pressed only because sending no key at all is not possible.
        o1.find('a').send_keys(:shift)

        o1.drag_to(o2, html5: true)

        wait_for_gql('apps/desktop/entities/user/current/graphql/mutations/userCurrentTaskbarItemListPrio.graphql')

        expect(page).to have_text("Received call\nTest initial changed")
      end

      logout

      login(username: agent.login, password: 'test')

      within '#user-taskbar-tabs' do
        expect(page).to have_text("Received call\nTest initial changed")
      end
    end
  end

  context 'when editing a title that wraps' do
    let(:ticket) { create(:ticket, group:, title: Array.new(7, 'A rather long ticket title').join(' ')) }

    before do
      article

      visit "/ticket/#{ticket.id}"
      wait_for_form_to_settle("form-ticket-edit-#{ticket.id}")
    end

    it 'keeps the title wrapped, with the caret where it was clicked' do
      within '[data-test-id="ticket-detail-top-bar-full-details"]' do
        label = find('[role="heading"]', text: ticket.title)
        label.click(x: 5, y: 5, offset: :top_left)

        field       = find('textarea:focus')
        line_height = field.evaluate_script('parseFloat(getComputedStyle(this).lineHeight)')

        expect(field.evaluate_script('this.selectionStart')).to be < 'A rather'.length
        expect(field.evaluate_script('this.getBoundingClientRect().height')).to be > line_height
      end
    end
  end
end
