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

require 'rails_helper'

RSpec.describe 'Ticket > Update > Full Quote Header', current_user_id: -> { current_user.id }, time_zone: 'Europe/London', type: :system do
  let(:group)                     { Group.find_by(name: 'Users') }
  let(:ticket)                    { create(:ticket, group: group) }
  let(:ticket_article)            { create(:ticket_article, ticket: ticket, from: 'Example Name <asdf1@example.com>') }
  let(:customer)                  { create(:customer) }
  let(:current_user)              { customer }
  let(:selection)                 { '' }
  let(:setting_ticket_email_from) { 'AgentNameSystemAddressName' }
  let(:setting_user_name_format)  { 'first_last' }

  prepend_before do
    Setting.set 'ui_ticket_zoom_article_email_full_quote_header', full_quote_header_setting
    Setting.set 'ticket_define_email_from', setting_ticket_email_from
    Setting.set 'user_name_format', setting_user_name_format
  end

  before do
    visit "ticket/zoom/#{ticket_article.ticket.id}"
  end

  context 'when "ui_ticket_zoom_article_email_full_quote_header" is enabled' do
    let(:full_quote_header_setting) { true }

    it 'includes sender when forwarding' do
      within(:active_content) do
        click_forward

        within(:richtext) do
          expect(page).to contain_full_quote(ticket_article).formatted_for(:forward)
        end
      end
    end

    it 'includes sender when replying' do
      within(:active_content) do
        highlight_and_click_reply

        within(:richtext) do
          expect(page).to contain_full_quote(ticket_article).formatted_for(:reply)
        end
      end
    end

    it 'includes sender when article visibility toggled' do
      within(:active_content) do
        set_internal
        highlight_and_click_reply

        within(:richtext) do
          expect(page).to contain_full_quote(ticket_article).formatted_for(:reply)
        end
      end
    end

    context 'when customer is agent' do
      let(:customer) { create(:agent) }

      it 'includes sender without email when forwarding' do
        within(:active_content) do
          click_forward

          within(:richtext) do
            expect(page).to contain_full_quote(ticket_article).formatted_for(:forward).ensuring_privacy(true)
          end
        end
      end
    end

    # https://github.com/zammad/zammad/issues/3824
    context 'when TO contains multiple senders and one of them is a known Zammad user' do
      let(:customer) { create(:customer) }
      let(:to_1) { "#{customer.fullname} <#{customer.email}>" }
      let(:to_2) { 'Example Two <two@example.org>' }

      let(:ticket_article) { create(:ticket_article, ticket: ticket, to: [to_1, to_2].join(', ')) }

      it 'includes all TO email address' do
        within(:active_content) do
          click_forward

          within(:richtext) do
            expect(page).to have_text(to_1).and(have_text(to_2))
          end
        end
      end
    end

    context 'when TO contains a quoted display name with a comma' do
      let(:current_user)     { create(:agent, groups: [group]) }
      let(:recipient_agent)  { create(:agent, firstname: 'John', lastname: 'Doe', groups: [group]) }
      # The recipient owns the ticket, so the browser has the record from the
      #   ticket assets rather than from a later collection push.
      let(:ticket)           { create(:ticket, group: group, owner: recipient_agent) }
      let(:ticket_article)   { create(:ticket_article, :inbound_email, ticket: ticket, to: %("Doe, John" <#{recipient_agent.email}>, other@example.org)) }

      it 'renders the recipient name without fragments' do
        within(:active_content) do
          click_forward

          within(:richtext) do
            expect(page).to have_text('To: John Doe, other@example.org')
            expect(page).to have_no_text('"Doe')
            expect(page).to have_no_text(recipient_agent.email)
          end
        end
      end
    end

    context "when user_name_format is 'last_first_comma' and a customer is the author" do
      let(:current_user)             { create(:agent, groups: [group]) }
      let(:setting_user_name_format) { 'last_first_comma' }
      let(:author)                   { create(:customer, firstname: 'Nicole', lastname: 'Braun') }
      let(:ticket)                   { create(:ticket, group: group, customer: author) }
      let(:ticket_article)           { create(:ticket_article, :inbound_email, ticket: ticket, created_by: author, origin_by: author, from: "Nicole Braun <#{author.email}>") }

      it 'orders the citation name like the desktop view does' do
        within(:active_content) do
          highlight_and_click_reply

          within(:richtext) do
            expect(page).to have_text('Braun, Nicole wrote:')
          end
        end
      end

      it 'orders the quoted From line accordingly on forward' do
        within(:active_content) do
          click_forward

          within(:richtext) do
            expect(page).to have_text(%(From: "Braun, Nicole" <#{author.email}>))
          end
        end
      end
    end

    # Inbound mails are created by user 1, the postmaster - its placeholder
    #   identity must not shadow the sender named in the header.
    context 'when an inbound mail was created by the system user', current_user_id: 1 do
      let(:author)         { create(:customer, firstname: 'Nicole', lastname: 'Braun') }
      let(:ticket)         { create(:ticket, group: group, customer: author) }
      let(:ticket_article) { create(:ticket_article, :inbound_email, ticket: ticket, from: "Nicole Braun <#{author.email}>") }

      it 'resolves the sender through the header on forward' do
        within(:active_content) do
          click_forward

          within(:richtext) do
            expect(page).to have_text("From: Nicole Braun <#{author.email}>")
            expect(page).to have_no_text('"-"')
          end
        end
      end
    end

    # Mirrors the GraphQL path, which renders the agent name only when no sender
    #   address is resolvable, instead of exposing the raw header.
    context 'when the group email address is not available in the browser' do
      let(:current_user)   { create(:agent, firstname: 'Max', lastname: 'Mustermann', groups: [group]) }
      let(:ticket_article) do
        create(:ticket_article, :outbound_web, ticket: ticket).tap do |article|
          article.update_columns(from: 'Max Private <max.private@example.com>')
        end
      end

      before do
        page.execute_script('App.EmailAddress.deleteAll()')
      end

      it 'renders the agent name only on forward' do
        within(:active_content) do
          click_forward

          within(:richtext) do
            expect(page).to have_text('From: Max Mustermann')
            expect(page).to have_no_text(ticket.group.email_address.name)
            expect(page).to have_no_text('max.private@example.com')
          end
        end
      end

      it 'renders the agent name in the reply citation' do
        within(:active_content) do
          highlight_and_click_reply

          within(:richtext) do
            expect(page).to have_text('Max Mustermann wrote:')
            expect(page).to have_no_text('undefined')
          end
        end
      end
    end

    context 'ticket is created by agent on behalf of customer' do
      let(:agent)          { create(:agent) }
      let(:current_user)   { agent }
      let(:ticket)         { create(:ticket, group: group, title: 'Created by agent on behalf of a customer', customer: customer) }
      let(:ticket_article) { create(:ticket_article, ticket: ticket, from: 'Created by agent on behalf of a customer', origin_by_id: customer.id) }

      it 'includes sender without email when replying' do
        within(:active_content) do
          highlight_and_click_reply

          within(:richtext) do
            expect(page).to contain_full_quote(ticket_article).formatted_for(:reply)
          end
        end
      end
    end

    # https://github.com/zammad/zammad/issues/3855
    context 'when ticket article has no recipient' do
      shared_examples 'when recipient is set to' do |recipient:, recipient_human:|
        context "when recipient is set to #{recipient_human}" do
          let(:ticket_article) { create(:ticket_article, :inbound_web, ticket: ticket, to: recipient) }

          it 'allows to forward without original recipient present' do
            within(:active_content) do
              click_forward

              within(:richtext) do
                expect(page).to contain_full_quote(ticket_article).formatted_for(:forward)
              end
            end
          end
        end
      end

      include_examples 'when recipient is set to', recipient: '', recipient_human: 'empty string'
      include_examples 'when recipient is set to', recipient: nil, recipient_human: 'nil'
    end
  end

  context 'when "ui_ticket_zoom_article_email_full_quote_header" is disabled' do
    let(:full_quote_header_setting) { false }

    it 'does not include sender when forwarding' do
      within(:active_content) do
        click_forward

        within(:richtext) do
          expect(page).not_to contain_full_quote(ticket_article).formatted_for(:forward)
        end
      end
    end

    it 'does not include sender when replying' do
      within(:active_content) do
        highlight_and_click_reply

        within(:richtext) do
          expect(page).not_to contain_full_quote(ticket_article).formatted_for(:reply)
        end
      end
    end
  end

  context 'when text is selected on page while replying' do
    let(:full_quote_header_setting) { false }
    let(:before_article_content_selector) { '.ticketZoom-header' }
    let(:after_article_content_selector)  { '.ticket-article-item .humanTimeFromNow' }
    let(:article_content_selector)        { '.ticket-article-item .richtext-content' }

    it 'does not quote article when bits other than the article are selected' do
      within(:active_content) do
        highlight_text(before_article_content_selector, '')
        click_reply

        within(:richtext) do
          expect(page).to have_no_text("Test Ticket\nTicket##{ticket.number} - created just now")
        end
      end
    end

    it 'quotes article when bits inside the article are selected' do
      within(:active_content) do
        highlight_text(article_content_selector, '')
        click_reply

        within(:richtext) do
          expect(page).to have_text('some message 123')
        end
      end
    end

    it 'quotes only article when bits before the article are selected as well' do
      within(:active_content) do
        highlight_text(before_article_content_selector, article_content_selector)

        click_reply

        within(:richtext) do
          expect(page).to have_no_text("Test Ticket\nTicket##{ticket.number} - created just now\nsome message 123")
          expect(page).to have_text('some message 123')
        end
      end
    end

    it 'quotes only article when bits after the article are selected as well' do
      within(:active_content) do
        highlight_text(article_content_selector, after_article_content_selector)

        click_reply

        within(:richtext) do
          expect(page).to have_no_text("some message 123\njust now")
          expect(page).to have_text('some message 123')
        end
      end
    end

    it 'quotes only article when bits both before and after the article are selected as well' do
      within(:active_content) do
        highlight_text(before_article_content_selector, after_article_content_selector)

        click_reply

        within(:richtext) do
          expect(page).to have_no_text("Test Ticket\nTicket##{ticket.number} - created just now\nsome message 123\njust now")
          expect(page).to have_text('some message 123')
        end
      end
    end

    context 'when bits inside a preformatted block are selected' do
      let(:ticket_article) do
        create(:ticket_article, ticket: ticket, content_type: 'text/html',
                                body: "<p>Hello,</p><pre>One\nTwo\nThree</pre>")
      end

      it 'keeps the line breaks in the quote' do
        within(:active_content) do
          highlight_text('.ticket-article-item .richtext-content pre', '.ticket-article-item .richtext-content pre')
          click_reply

          within(:richtext) do
            expect(page).to have_css('blockquote pre', text: "One\nTwo\nThree")
          end
        end
      end
    end

    context 'when full quote header setting is enabled' do
      let(:full_quote_header_setting) { true }

      it 'can breakout with enter from quote block' do
        within(:active_content) do
          highlight_and_click_reply

          within(:richtext) do
            wait.until do
              first('blockquote br:nth-child(2)', visible: :all)
            end
            blockquote_empty_line = first('blockquote br:nth-child(2)', visible: :all)
            place_cursor_before(blockquote_empty_line)
          end

          find(:richtext).send_keys(:enter)

          within(:richtext) do
            expect(page).to have_css('blockquote', count: 2)
          end
        end
      end
    end
  end

  # https://github.com/zammad/zammad/issues/5130
  context 'when sender format is switched' do
    let(:full_quote_header_setting) { true }
    let(:sender_agent)              { create(:agent) }
    let(:sender_outbound_article)   { create(:ticket_article, :outbound_email, ticket: ticket, created_by_id: sender_agent.id, origin_by_id: sender_agent.id, body: SecureRandom.hex(8)) }

    # Created before the ticket is opened, otherwise the article only shows up via a push.
    let(:ticket_article) { super().tap { sender_outbound_article } }

    # The recipient (To/CC) rendering must not depend on the sender format, so the
    #   shared examples pin it for every format value.
    shared_examples 'renders agent recipients name only' do
      context 'when an agent is a recipient' do
        let(:recipient_agent) { create(:agent, groups: [group]) }
        let(:ticket)          { create(:ticket, group: group, owner: recipient_agent) }
        let(:sender_outbound_article) do
          create(:ticket_article, :outbound_email,
                 ticket:        ticket,
                 created_by_id: sender_agent.id,
                 origin_by_id:  sender_agent.id,
                 to:            "#{recipient_agent.fullname} <#{recipient_agent.email}>",
                 body:          SecureRandom.hex(8))
        end

        it 'does show agent recipient name only on forward' do
          expect(page).to have_text(sender_outbound_article.body)

          click_forward(sender_outbound_article)
          expect(page.find('.js-writeArea')).to have_text("To: #{recipient_agent.fullname}")
          expect(page.find('.js-writeArea')).to have_no_text(recipient_agent.email)
          expect(page.find('.js-writeArea')).to have_no_text("#{recipient_agent.fullname} #{Setting.get('ticket_define_email_from_separator')}")
        end
      end
    end

    context 'when setting value is SystemAddressName' do
      let(:setting_ticket_email_from) { 'SystemAddressName' }

      it 'does not show agent name on forward' do
        expect(page).to have_text(sender_outbound_article.body)

        click_forward(sender_outbound_article)
        expect(page.find('.js-writeArea')).to have_text("From: #{ticket.group.email_address.name} <#{ticket.group.email_address.email}>")
        expect(page.find('.js-writeArea')).to have_no_text("From: #{sender_agent.fullname}")
      end

      include_examples 'renders agent recipients name only'
    end

    context 'when setting value is AgentNameSystemAddressName' do
      let(:setting_ticket_email_from) { 'AgentNameSystemAddressName' }

      it 'does show agent name on forward' do
        expect(page).to have_text(sender_outbound_article.body)

        click_forward(sender_outbound_article)
        expect(page.find('.js-writeArea')).to have_text("From: #{sender_agent.fullname} #{Setting.get('ticket_define_email_from_separator')} #{ticket.group.email_address.name} <#{ticket.group.email_address.email}>")
        expect(page.find('.js-writeArea')).to have_no_text("From: #{ticket.group.email_address.name} <#{ticket.group.email_address.email}>")
      end

      context 'when the agent has no name' do
        let(:sender_agent) { create(:agent, firstname: nil, lastname: nil, email: 'namelessagent@example.com') }

        it 'falls back to the system address display name on forward' do
          expect(page).to have_text(sender_outbound_article.body)

          click_forward(sender_outbound_article)
          expect(page.find('.js-writeArea')).to have_text("From: #{ticket.group.email_address.name} <#{ticket.group.email_address.email}>")
          expect(page.find('.js-writeArea')).to have_no_text(sender_agent.email)
        end
      end

      include_examples 'renders agent recipients name only'
    end

    context 'when setting value is AgentName' do
      let(:setting_ticket_email_from) { 'AgentName' }

      it 'does show agent name with group email address on forward' do
        expect(page).to have_text(sender_outbound_article.body)

        click_forward(sender_outbound_article)
        expect(page.find('.js-writeArea')).to have_text("From: #{sender_agent.fullname} <#{ticket.group.email_address.email}>")
        expect(page.find('.js-writeArea')).to have_no_text(sender_agent.email)
      end

      context 'when an agent is a recipient' do
        let(:sender_outbound_article) do
          create(:ticket_article, :outbound_email,
                 ticket:        ticket,
                 created_by_id: sender_agent.id,
                 origin_by_id:  sender_agent.id,
                 to:            "#{sender_agent.fullname} <#{sender_agent.email}>",
                 body:          SecureRandom.hex(8))
        end

        it 'does show agent recipient without email address on forward' do
          expect(page).to have_text(sender_outbound_article.body)

          click_forward(sender_outbound_article)
          expect(page.find('.js-writeArea')).to have_text("To: #{sender_agent.fullname}")
          expect(page.find('.js-writeArea')).to have_no_text(sender_agent.email)
        end

        context 'when the agent has no name' do
          let(:sender_agent) { create(:agent, firstname: nil, lastname: nil, email: 'namelessagent@example.com') }

          # The To header Zammad itself generates for such users is the quoted
          #   form '"user@example.com" <user@example.com>'.
          let(:sender_outbound_article) do
            create(:ticket_article, :outbound_email,
                   ticket:        ticket,
                   created_by_id: sender_agent.id,
                   origin_by_id:  sender_agent.id,
                   to:            Channel::EmailBuild.recipient_line(sender_agent.fullname, sender_agent.email),
                   body:          SecureRandom.hex(8))
          end

          it 'does not fall back to the agent email address on forward' do
            expect(page).to have_text(sender_outbound_article.body)

            click_forward(sender_outbound_article)
            expect(page.find('.js-writeArea')).to have_text("From: #{ticket.group.email_address.name} <#{ticket.group.email_address.email}>")
            expect(page.find('.js-writeArea')).to have_text('To: Agent')
            expect(page.find('.js-writeArea')).to have_no_text(sender_agent.email)
          end
        end
      end
    end

    context 'when the mail was sent from a different email address' do
      let(:setting_ticket_email_from) { 'AgentName' }
      let(:other_email_address)       { create(:email_address) }
      let(:ticket_article) do
        create(:ticket_article, :outbound_email, ticket: ticket, created_by_id: sender_agent.id, origin_by_id: sender_agent.id).tap do |article|
          article.update!(preferences: article.preferences.merge('email_address_id' => other_email_address.id))
        end
      end

      it 'prefers the recorded address over the group address on forward' do
        click_forward

        expect(page.find('.js-writeArea')).to have_text("From: #{sender_agent.fullname} <#{other_email_address.email}>")
        expect(page.find('.js-writeArea')).to have_no_text(ticket.group.email_address.email)
      end

      context "when sender format is 'SystemAddressName'" do
        let(:setting_ticket_email_from) { 'SystemAddressName' }

        it 'prefers the recorded address name in the reply citation' do
          highlight_and_click_reply

          within(:richtext) do
            expect(page).to have_text("#{other_email_address.name} wrote:")
            expect(page).to have_no_text("#{ticket.group.email_address.name} wrote:")
          end
        end
      end
    end
  end

  # Scoped to one article where the ticket shows several.
  def click_forward(article = nil)
    return click '.js-ArticleAction[data-type=emailForward]' if !article

    within(:active_ticket_article, article) { click '.js-ArticleAction[data-type=emailForward]' }
  end

  def set_internal
    click '.js-ArticleAction[data-type=internal]'
  end

  def click_reply
    click '.js-ArticleAction[data-type=emailReply]'
  end

  def highlight_text(start_selector, end_selector)
    find(start_selector)
      .execute_script(<<~JAVASCRIPT, end_selector)
        let [ end_selector ] = arguments
        let end_node = $(end_selector)[0]
        if(!end_node) {
          end_node = this.nextSibling
        }
        window.getSelection().removeAllRanges()
        var range = window.document.createRange()
        range.setStart(this, 0)
        range.setEnd(end_node, end_node.childNodes.length)
        window.getSelection().addRange(range)
      JAVASCRIPT
  end

  def highlight_and_click_reply
    find('.ticket-article-item .richtext-content')
      .execute_script <<~JAVASCRIPT
        window.getSelection().removeAllRanges()
        var range = window.document.createRange()
        range.setStart(this, 0)
        range.setEnd(this.nextSibling, 0)
        window.getSelection().addRange(range)
      JAVASCRIPT

    wait.until_constant do
      find('.ticket-article-item .richtext-content').evaluate_script('window.getSelection().toString().trim()')
    end

    click_reply

    within(:richtext) do
      find('blockquote', visible: :all)
    end
  end

  define :contain_full_quote do
    match do
      confirm_content && confirm_style
    end

    match_when_negated do
      confirm_no_content
    end

    # sets expected quote format
    # @param [Symbol] :forward or :reply, defaults to :reply if not set
    chain :formatted_for do |style|
      @style = style
    end

    failure_message do
      if !confirm_style
        string = "expected\n```\n#{citation_text}\n```\nto match "

        case style
        when :reply
          string += '`On...wrote:`'
        when :forward
          string += '`Subject \n Date`'
        end

        return string
      end

      string = "expected\n```\n#{citation_text}\n```\nto "

      case style
      when :reply
        string += "have name `#{name}` and timestamp `#{timestamp_reply}`"

        string += ' but has no name' if citation_text.exclude?(name)
        string += ' but has no timestamp' if !includes_timestamp?(citation_text, timestamp_reply)
      when :forward
        string += "have name `#{name}` and timestamp `#{timestamp_forward}`"

        string += ensure_privacy? ? ' with no email' : " with email `#{email}`"

        string += ' but has no name' if citation_text.exclude?(name)
        string += ' but has no timestamp' if !includes_timestamp?(citation_text, timestamp_forward)
        string += ' but has no email' if !ensure_privacy? && citation_text.include?(email)
      end

      string
    end

    failure_message_when_negated do
      "expected\n```\n#{citation_text}\n```\nto not contain name/email/timestamp"
    end

    def style
      @style || :reply # rubocop:disable RSpec/InstanceVariable
    end

    # sets expected privacy level
    # @param [Boolean] defaults to false if not set
    chain :ensuring_privacy do |flag|
      @ensuring_privacy = flag
    end

    def ensure_privacy?
      @ensuring_privacy || false # rubocop:disable RSpec/InstanceVariable
    end

    def confirm_content
      case style
      when :reply
        confirm_content_reply
      when :forward
        confirm_content_forward
      end
    end

    def confirm_content_reply
      citation_text.include?(name) &&
        citation_text.exclude?(email) &&
        includes_timestamp?(citation_text, timestamp_reply)
    end

    def confirm_content_forward
      citation_text.include?(name) &&
        includes_timestamp?(citation_text, timestamp_forward) &&
        (ensure_privacy? ? citation_text.exclude?(email) : citation_text.include?(email))
    end

    def confirm_no_content
      citation_text.exclude?(name) &&
        citation_text.exclude?(email) &&
        citation_text.exclude?(timestamp_reply) &&
        citation_text.exclude?(timestamp_forward)
    end

    def confirm_style
      case style
      when :forward
        citation_text.match?(%r{Subject(.+)\nDate(.+)})
      when :reply
        citation_text.match?(%r{^On(.+)wrote:$})
      end
    end

    def citation
      actual.first('blockquote[type=cite]')
    end

    delegate :text, to: :citation, prefix: true

    def name
      (expected.origin_by || expected.created_by).fullname
    end

    def email
      expected.created_by.email
    end

    def timestamp_reply
      expected
        .created_at
        .in_time_zone('Europe/London')
        .strftime('%A, %B %1d, %Y at %1I:%M:%S %p')
    end

    def timestamp_forward
      expected
        .created_at
        .in_time_zone('Europe/London')
        .strftime('%m/%d/%Y %1I:%M %P')
    end

    # Chrome started to use non-breaking-space before AM/PM
    # While Firefox still has regular space
    # Using regexp with :space: to match either
    def includes_timestamp?(string, timestamp)
      regexp = Regexp.new timestamp.gsub(' ', '[[:space:]]{1}')

      string.match? regexp
    end
  end
end
