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

require 'rails_helper'

RSpec.describe TriggerWebhookJob, type: :job do

  let(:endpoint)    { 'http://api.example.com/webhook' }
  let(:resolved_ip) { '8.8.8.8' }
  let(:token)       { 's3cr3t-t0k3n' }
  let(:webhook)     { build(:webhook, endpoint: endpoint, signature_token: token).tap { it.save(validate: false) } }
  let(:trigger) do
    create(:trigger,
           perform: {
             'notification.webhook' => { 'webhook_id' => webhook.id }
           })
  end

  before do
    allow(IPSocket)
      .to receive(:getaddress)
      .with('api.example.com')
      .and_return(resolved_ip)
  end

  context 'when serialized model argument gets deleted' do

    subject!(:job) do
      described_class.perform_later(
        trigger,
        ticket,
        article,
        changes:        nil,
        user_id:        nil,
        execution_type: nil,
        event_type:     nil,
      )
    end

    let(:ticket) { create(:ticket) }
    let(:article) { create(:'ticket/article') }

    shared_examples 'handle deleted argument models' do
      it 'raises no error' do
        expect { ActiveJob::Base.execute job.serialize }.not_to raise_error
      end

      it "doesn't perform request" do
        allow(UserAgent).to receive(:post)
        ActiveJob::Base.execute job.serialize
        expect(UserAgent).not_to have_received(:post)
      end
    end

    context 'when Trigger gets deleted' do
      before { trigger.destroy! }

      include_examples 'handle deleted argument models'
    end

    context 'when Ticket gets deleted' do
      before { ticket.destroy! }

      include_examples 'handle deleted argument models'
    end

    context 'when Article gets deleted' do
      before { article.destroy! }

      include_examples 'handle deleted argument models'
    end
  end

  describe '#perform' do
    subject(:perform) do
      described_class.perform_now(
        trigger,
        ticket,
        article,
        changes:        nil,
        user_id:        nil,
        execution_type: nil,
        event_type:     nil,
      )
    end

    # The job builds its payload in a system context, so the expectation has to be built the
    # same way - otherwise it would compare against redacted attributes.
    let(:payload_ticket) { UserInfo.with_system_context { TriggerWebhookJob::RecordPayload.generate(ticket) } }
    let(:payload_article) { UserInfo.with_system_context { TriggerWebhookJob::RecordPayload.generate(article) } }

    let!(:ticket) { create(:ticket) }
    let!(:article) { create(:'ticket/article') }

    let(:response_status) { 200 }
    let(:payload) do
      {
        ticket:  payload_ticket,
        article: payload_article,
      }
    end

    let(:headers) do
      {
        'Content-Type'     => 'application/json; charset=utf-8',
        'User-Agent'       => 'Zammad User Agent',
        'X-Zammad-Trigger' => trigger.name,
      }
    end

    let(:response_body) do
      {}.to_json
    end

    let(:response_headers) { {} }

    before do
      allow(Rails.logger).to receive(:error)

      stub_request(:post, endpoint).to_return(headers: response_headers, status: response_status, body: response_body)

      perform
    end

    context 'with trigger token configured' do
      it 'includes X-Hub-Signature header' do
        expect(WebMock).to have_requested(:post, endpoint)
          .with(body: payload, headers: headers)
          .with { |req| req.headers['X-Zammad-Delivery'].is_a?(String) }
          .with { |req| req.headers['X-Hub-Signature'].is_a?(String) }
      end
    end

    context 'without trigger token configured' do
      let(:token) { nil }

      it "doesn't include X-Hub-Signature header" do
        expect(WebMock).to have_requested(:post, endpoint)
          .with(body: payload, headers: headers)
          .with { |req| req.headers['X-Zammad-Delivery'].is_a?(String) }
          .with { |req| !req.headers.key?('X-Hub-Signature') }
      end
    end

    context 'with HTTP BasicAuth configured' do
      let(:webhook) { create(:webhook, endpoint: endpoint, basic_auth_username: 'user', basic_auth_password: 'passw0rd') }

      it 'generates a request with Authorization header' do
        expect(WebMock).to have_requested(:post, endpoint)
          .with(body: payload, headers: headers)
          .with { |req| req.headers['Authorization'] == "Basic #{Base64.strict_encode64('user:passw0rd')}" }
      end
    end

    context 'without HTTP BasicAuth configured' do
      let(:webhook)  { create(:webhook, endpoint: endpoint) }

      it 'generates a request without Authorization header' do
        expect(WebMock).to have_requested(:post, endpoint)
          .with(body: payload, headers: headers)
          .with { |req| !req.headers.key?('Authorization') }
      end
    end

    context 'with Bearer Token configured' do
      let(:webhook) { create(:webhook, endpoint: endpoint, bearer_token: 'secret-bearer-token-123') }

      it 'generates a request with Bearer Authorization header' do
        expect(WebMock).to have_requested(:post, endpoint)
          .with(body: payload, headers: headers)
          .with { |req| req.headers['Authorization'] == 'Bearer secret-bearer-token-123' }
      end
    end

    context 'without Bearer Token configured' do
      let(:webhook)  { create(:webhook, endpoint: endpoint) }

      it 'generates a request without Bearer Authorization header' do
        expect(WebMock).to have_requested(:post, endpoint)
          .with(body: payload, headers: headers)
          .with { |req| !req.headers.key?('Authorization') }
      end
    end

    context 'with different HTTP methods' do
      %w[post put patch delete].each do |method|
        context "with #{method.upcase} method" do
          let(:webhook) { create(:webhook, endpoint: endpoint, http_method: method) }

          before do
            stub_request(method.to_sym, endpoint).to_return(headers: response_headers, status: response_status, body: response_body)
            perform
          end

          it "makes a #{method.upcase} request" do
            expect(WebMock).to have_requested(method.to_sym, endpoint)
          end
        end
      end
    end

    context 'when response is not JSON' do

      let(:response_body) { 'Thanks!' }

      it 'succeeds anyway' do
        expect(described_class).not_to have_been_enqueued
      end
    end

    context "when request doesn't succeed" do
      let(:response_status) { 404 }

      it 'enqueues job again' do
        expect(described_class).to have_been_enqueued
      end
    end

    it 'attributes the HTTP log to the webhook' do
      expect(HttpLog.last.related_object).to eq(webhook)
    end

    context 'when response is a redirect' do
      let(:response_status)  { 301 }
      let(:response_headers) { { Location: 'http://redirect.target/' } }

      it 'enqueues job again due to redirect exception', :aggregate_failures do
        expect(described_class).to have_been_enqueued
        expect(HttpLog.last.response).to include('code' => 0, 'content' => '')
      end
    end

    context 'with different payloads' do
      subject(:perform) do
        described_class.perform_now(
          trigger,
          ticket,
          article,
          changes:        nil,
          user_id:        nil,
          execution_type: 'trigger',
          event_type:     'info',
        )
      end

      let(:webhook)                  { create(:webhook, endpoint: endpoint, customized_payload: customized_payload, custom_payload: custom_payload, pre_defined_webhook_type: pre_defined_webhook_type) }
      let(:customized_payload)       { false }
      let(:custom_payload)           { nil }
      let(:pre_defined_webhook_type) { nil }

      def pre_defined_webhook_payload
        tracks = { ticket: ticket, article: article }
        data = {
          event:   {
            type:      'info',
            execution: 'trigger',
            changes:   nil,
            user_id:   nil,
          },
          webhook: webhook
        }

        # Get predefined payload from the new track system
        predefined_payload = Service::Template::Interpolation::Interpolator::Webhook::Track::PreDefinedWebhook.payload('Mattermost')

        # Use the new interpolation service
        interpolator = Service::Template::Interpolation::Interpolator::Webhook.new( # rubocop:disable Zammad/ForbidCallingServiceDirectly
          template:                       predefined_payload,
          tracks:                         tracks,
          additional_track_generate_data: data,
        )

        interpolator.execute
      end

      shared_examples 'including correct payload' do
        it 'includes correct payload' do
          expect(WebMock).to have_requested(:post, endpoint)
            .with(body: payload, headers: headers)
        end
      end

      context 'with non-customized payload' do
        it_behaves_like 'including correct payload'

        context 'with pre-defined webhook' do
          let(:webhook) { create(:mattermost_webhook, endpoint: endpoint) }
          let(:payload) { pre_defined_webhook_payload }

          it_behaves_like 'including correct payload'
        end
      end

      context 'with customized payload' do
        let(:customized_payload) { true }
        let(:custom_payload)     { '{"ticket":"#{ticket.title}"}' } # rubocop:disable Lint/InterpolationCheck
        let(:payload) do
          {
            ticket: ticket.title,
          }
        end

        it_behaves_like 'including correct payload'

        context 'with pre-defined webhook' do
          let(:webhook) { create(:mattermost_webhook, endpoint: endpoint, customized_payload:, custom_payload:) }

          it_behaves_like 'including correct payload'
        end

        context 'with empty custom payload' do
          let(:custom_payload) { nil }
          let(:payload) do
            {
              ticket:  payload_ticket,
              article: payload_article,
            }
          end

          it_behaves_like 'including correct payload'

          context 'with pre-defined webhook' do
            let(:webhook) { create(:mattermost_webhook, endpoint: endpoint) }
            let(:payload) { pre_defined_webhook_payload }

            it_behaves_like 'including correct payload'
          end
        end
      end
    end

    context 'with endpoint variable interpolation' do
      let(:endpoint) { 'http://api.example.com/webhook/tickets/#{ticket.id}' } # rubocop:disable Lint/InterpolationCheck
      let(:expected_endpoint) { "http://api.example.com/webhook/tickets/#{ticket.id}" }

      before do
        stub_request(:post, expected_endpoint).to_return(status: response_status, body: response_body)
        perform
      end

      it 'interpolates ticket variables in the endpoint' do
        expect(WebMock).to have_requested(:post, expected_endpoint)
      end

      context 'with multiple variables' do
        let(:endpoint) { 'http://api.example.com/webhook?ticket=#{ticket.number}&id=#{ticket.id}' } # rubocop:disable Lint/InterpolationCheck
        let(:expected_endpoint) { "http://api.example.com/webhook?ticket=#{ticket.number}&id=#{ticket.id}" }

        it 'interpolates all variables correctly' do
          expect(WebMock).to have_requested(:post, expected_endpoint)
        end
      end

      context 'with special characters requiring URL encoding' do
        before do
          ticket.update!(title: 'Test Ticket #123: Special & Characters')
        end

        let(:endpoint) { 'http://api.example.com/webhook?title=#{ticket.title}' } # rubocop:disable Lint/InterpolationCheck
        let(:expected_endpoint) { "http://api.example.com/webhook?title=#{CGI.escape(ticket.title)}" }

        it 'URL-encodes the interpolated values' do
          expect(WebMock).to have_requested(:post, expected_endpoint)
        end
      end

      context 'without variables' do
        let(:endpoint) { 'http://api.example.com/webhook/static' }

        it 'uses the endpoint as-is' do
          expect(WebMock).to have_requested(:post, endpoint)
        end
      end
    end

    context 'with multiple webhooks configured and an explicit webhook_id' do
      subject(:perform) do
        described_class.perform_now(
          trigger,
          ticket,
          article,
          webhook_id:     other_webhook.id,
          changes:        nil,
          user_id:        nil,
          execution_type: nil,
          event_type:     nil,
        )
      end

      let(:other_endpoint) { 'http://api.example.com/other-webhook' }
      let(:other_webhook)  { build(:webhook, endpoint: other_endpoint, signature_token: token).tap { it.save(validate: false) } }
      let(:trigger) do
        create(:trigger,
               perform: {
                 'notification.webhook' => { 'webhook_id' => [webhook.id.to_s, other_webhook.id.to_s] }
               })
      end

      before do
        stub_request(:post, other_endpoint).to_return(headers: response_headers, status: response_status, body: response_body)
        perform
      end

      it 'requests only the explicitly passed webhook', :aggregate_failures do
        expect(WebMock).to have_requested(:post, other_endpoint)
        expect(WebMock).not_to have_requested(:post, endpoint)
      end
    end

    context 'without an explicit webhook_id (legacy job enqueued before multi-webhook change)' do
      it 'falls back to the webhook configured in the trigger' do
        expect(WebMock).to have_requested(:post, endpoint)
      end

      context 'when the trigger stores the webhook id as an array' do
        let(:trigger) do
          create(:trigger,
                 perform: {
                   'notification.webhook' => { 'webhook_id' => [webhook.id.to_s] }
                 })
        end

        it 'falls back to the first configured webhook' do
          expect(WebMock).to have_requested(:post, endpoint)
        end
      end
    end

    context 'when endpoint is unsafe' do
      let(:resolved_ip) { '1' }

      it 'logs an error' do
        expect(Rails.logger)
          .to have_received(:error)
          .with("Can't execute Webhook with ID #{webhook.id} for Trigger '#{trigger.name}' with ID #{trigger.id}: Could not ensure safety of the hostname: api.example.com")
      end

      it 'does not perform the request' do
        expect(WebMock)
          .not_to have_requested(:post, endpoint)
      end
    end
  end
end
