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

require 'rails_helper'

RSpec.describe 'Ticket Article API endpoints', type: :request do

  let(:admin) do
    create(:admin, groups: Group.all)
  end
  let!(:group) { create(:group) }

  let(:agent) do
    create(:agent, groups: Group.all)
  end
  let(:customer) do
    create(:customer)
  end

  describe 'request handling' do

    context 'when an agent adds articles to a ticket' do
      let(:ticket) { create(:ticket, group: Group.lookup(name: 'Users'), customer:) }

      before { authenticated_as(agent) }

      def create_article(**params)
        post '/api/v1/ticket_articles', params: { ticket_id: ticket.id, type: 'note' }.merge(params), as: :json
        expect(response).to have_http_status(:created)
        Ticket::Article.find(json_response['id'])
      end

      it 'creates a plain text note' do
        article = create_article(content_type: 'text/plain', body: 'some body')

        expect(article).to have_attributes(
          subject: nil, body: 'some body', content_type: 'text/plain',
          created_by_id: agent.id, updated_by_id: agent.id, attachments: be_empty
        )
      end

      it 'stores an inline image as an attachment', :aggregate_failures do
        article = create_article(content_type: 'text/html', body: 'some body <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />')

        expect(json_response['body']).to match(%r{some body <img src="/api/v1/ticket_attachment/.+?" alt="Red dot"})
        expect(article.attachments.sole).to have_attributes(
          filename:    'image1.png',
          size:        '21',
          preferences: include('Mime-Type' => 'image/png', 'Content-Disposition' => 'inline', 'Content-ID' => match(%r{@zammad.example.com}))
        )
      end

      it 'stores given attachments', :aggregate_failures do
        article = create_article(content_type: 'text/html', body: 'some body', attachments: [{ 'filename' => 'some_file.txt', 'data' => 'dGVzdCAxMjM=', 'mime-type' => 'text/plain' }])

        get "/api/v1/ticket_articles/#{article.id}?expand=true", params: {}, as: :json
        expect(json_response['attachments'].sole).to include(
          'id' => article.attachments.sole.id, 'filename' => 'some_file.txt', 'size' => '8', 'preferences' => include('Mime-Type' => 'text/plain')
        )
      end

      it 'stores given preferences' do
        article = create_article(content_type: 'text/plain', body: 'some body', internal: false, preferences: { some_key1: 123, highlight: '123' })

        expect(article.preferences).to include('some_key1' => 123, 'highlight' => '123')
      end

      it 'updates only the internal flag and the highlight on an existing article' do
        article = create_article(content_type: 'text/plain', body: 'some body', internal: false, preferences: { some_key1: 123, highlight: '123' })

        put "/api/v1/ticket_articles/#{article.id}", params: { body: 'some body 2', internal: true, preferences: { some_key2: 'abc', highlight: '234' } }, as: :json

        expect(article.reload).to have_attributes(
          body:        'some body',
          internal:    true,
          preferences: include('some_key1' => 123, 'highlight' => '234').and(not_include('some_key2'))
        )
      end
    end

    it 'does ticket create with customer and articles' do
      params = {
        title:   'a new ticket #2',
        group:   'Users',
        article: {
          body: 'some body',
        }
      }
      authenticated_as(customer)
      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:created)

      params = {
        ticket_id:    json_response['id'],
        content_type: 'text/plain', # or text/html
        body:         'some body',
        type:         'note',
      }
      post '/api/v1/ticket_articles', params: params, as: :json
      expect(response).to have_http_status(:created)
      expect(json_response).to be_a(Hash)
      expect(json_response['subject']).to be_nil
      expect(json_response['body']).to eq('some body')
      expect(json_response['content_type']).to eq('text/plain')
      expect(json_response['updated_by_id']).to eq(customer.id)
      expect(json_response['created_by_id']).to eq(customer.id)

      ticket = Ticket.find(json_response['ticket_id'])
      expect(ticket.articles.count).to eq(2)
      expect(ticket.articles[1].sender.name).to eq('Customer')
      expect(ticket.articles[0].attachments.count).to eq(0)
      expect(ticket.articles[1].attachments.count).to eq(0)

      params = {
        ticket_id:    json_response['ticket_id'],
        content_type: 'text/plain', # or text/html
        body:         'some body',
        sender:       'Agent',
        type:         'note',
      }
      post '/api/v1/ticket_articles', params: params, as: :json
      expect(response).to have_http_status(:created)
      expect(json_response).to be_a(Hash)
      expect(json_response['subject']).to be_nil
      expect(json_response['body']).to eq('some body')
      expect(json_response['content_type']).to eq('text/plain')
      expect(json_response['updated_by_id']).to eq(customer.id)
      expect(json_response['created_by_id']).to eq(customer.id)

      ticket.articles.reload

      ticket = Ticket.find(json_response['ticket_id'])
      expect(ticket.articles.count).to eq(3)
      expect(ticket.articles[2].sender.name).to eq('Customer')
      expect(ticket.articles[2].internal).to be(false)
      expect(ticket.articles[0].attachments.count).to eq(0)
      expect(ticket.articles[1].attachments.count).to eq(0)
      expect(ticket.articles[2].attachments.count).to eq(0)

      params = {
        ticket_id:    json_response['ticket_id'],
        content_type: 'text/plain', # or text/html
        body:         'some body 2',
        sender:       'Agent',
        type:         'note',
        internal:     true,
      }
      post '/api/v1/ticket_articles', params: params, as: :json
      expect(response).to have_http_status(:created)
      expect(json_response).to be_a(Hash)
      expect(json_response['subject']).to be_nil
      expect(json_response['body']).to eq('some body 2')
      expect(json_response['content_type']).to eq('text/plain')
      expect(json_response['updated_by_id']).to eq(customer.id)
      expect(json_response['created_by_id']).to eq(customer.id)

      ticket.articles.reload

      ticket = Ticket.find(json_response['ticket_id'])
      expect(ticket.articles.count).to eq(4)
      expect(ticket.articles[3].sender.name).to eq('Customer')
      expect(ticket.articles[3].internal).to be(false)
      expect(ticket.articles[0].attachments.count).to eq(0)
      expect(ticket.articles[1].attachments.count).to eq(0)
      expect(ticket.articles[2].attachments.count).to eq(0)
      expect(ticket.articles[3].attachments.count).to eq(0)

      # add internal article
      article = create(
        :ticket_article,
        ticket_id: ticket.id,
        internal:  true,
        sender:    Ticket::Article::Sender.find_by(name: 'Agent'),
        type:      Ticket::Article::Type.find_by(name: 'note'),
      )

      ticket.articles.reload

      expect(ticket.articles.count).to eq(5)
      expect(ticket.articles[4].sender.name).to eq('Agent')
      expect(ticket.articles[4].updated_by_id).to eq(1)
      expect(ticket.articles[4].created_by_id).to eq(1)
      expect(ticket.articles[0].attachments.count).to eq(0)
      expect(ticket.articles[1].attachments.count).to eq(0)
      expect(ticket.articles[2].attachments.count).to eq(0)
      expect(ticket.articles[3].attachments.count).to eq(0)
      expect(ticket.articles[4].attachments.count).to eq(0)

      get "/api/v1/ticket_articles/#{article.id}", params: {}, as: :json
      expect(response).to have_http_status(:forbidden)
      expect(json_response).to be_a(Hash)
      expect(json_response['error']).to eq('Not authorized')

      put "/api/v1/ticket_articles/#{article.id}", params: { internal: false }, as: :json
      expect(response).to have_http_status(:forbidden)
      expect(json_response).to be_a(Hash)
      expect(json_response['error']).to eq('Not authorized')

    end

    it 'does create phone ticket for customer and expected origin_by_id' do
      params = {
        title:       'a new ticket #1',
        group:       'Users',
        customer_id: customer.id,
        article:     {
          body:   'some body',
          sender: 'Customer',
          type:   'phone',
        }
      }
      authenticated_as(agent)
      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:created)
      expect(json_response).to be_a(Hash)
      expect(json_response['title']).to eq('a new ticket #1')

      expect(Ticket::Article.where(ticket_id: json_response['id']).count).to eq(2) # original + auto responder

      article = Ticket::Article.where(ticket_id: json_response['id']).first
      expect(article.origin_by_id).to eq(customer.id)
      expect(article.from).to be_in(
        [
          "#{customer.firstname} #{customer.lastname} <#{customer.email}>",
          "\"#{customer.firstname} #{customer.lastname}\" <#{customer.email}>"
        ]
      )
    end

    it 'does create phone ticket by customer and manipulate origin_by_id' do
      params = {
        title:       'a new ticket #1',
        group:       'Users',
        customer_id: customer.id,
        article:     {
          body:         'some body',
          sender:       'Customer',
          type:         'phone',
          origin_by_id: 1,
        }
      }
      authenticated_as(customer)
      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:created)
      expect(json_response).to be_a(Hash)

      expect(Ticket::Article.where(ticket_id: json_response['id']).count).to eq(1) # ony original

      article = Ticket::Article.where(ticket_id: json_response['id']).first
      expect(article.origin_by_id).to eq(customer.id)
    end

    it 'does ticket split with html - check attachments' do
      ticket = create(:ticket, group: group)
      article = create(
        :ticket_article,
        ticket_id:    ticket.id,
        type:         Ticket::Article::Type.lookup(name: 'note'),
        sender:       Ticket::Article::Sender.lookup(name: 'Customer'),
        body:         '<b>test</b> <img src="cid:15.274327094.140938@ZAMMAD.example.com"/> test <img src="cid:15.274327094.140938.3@ZAMMAD.example.com"/>',
        content_type: 'text/html',
      )
      create(:store,
             object:      'Ticket::Article',
             o_id:        article.id,
             data:        'content_file1_normally_should_be_an_image',
             filename:    'some_file1.jpg',
             preferences: {
               'Content-Type'        => 'image/jpeg',
               'Mime-Type'           => 'image/jpeg',
               'Content-ID'          => '15.274327094.140938@zammad.example.com',
               'Content-Disposition' => 'inline',
             })
      create(:store,
             object:      'Ticket::Article',
             o_id:        article.id,
             data:        'content_file2_normally_should_be_an_image',
             filename:    'some_file2.jpg',
             preferences: {
               'Content-Type'        => 'image/jpeg',
               'Mime-Type'           => 'image/jpeg',
               'Content-ID'          => '15.274327094.140938.2@zammad.example.com',
               'Content-Disposition' => 'inline',
             })
      create(:store,
             object:      'Ticket::Article',
             o_id:        article.id,
             data:        'content_file3_normally_should_be_an_image',
             filename:    'some_file3.jpg',
             preferences: {
               'Content-Type' => 'image/jpeg',
               'Mime-Type'    => 'image/jpeg',
               'Content-ID'   => '15.274327094.140938.3@zammad.example.com',
             })
      create(:store,
             object:      'Ticket::Article',
             o_id:        article.id,
             data:        'content_file4_normally_should_be_an_image',
             filename:    'some_file4.jpg',
             preferences: {
               'Content-Type' => 'image/jpeg',
               'Mime-Type'    => 'image/jpeg',
               'Content-ID'   => '15.274327094.140938.4@zammad.example.com',
             })
      create(:store,
             object:      'Ticket::Article',
             o_id:        article.id,
             data:        'content_file1_normally_should_be_an_pdf',
             filename:    'Rechnung_RE-2018-200.pdf',
             preferences: {
               'Content-Type'        => 'application/octet-stream; name="Rechnung_RE-2018-200.pdf"',
               'Mime-Type'           => 'application/octet-stream',
               'Content-ID'          => '8AB0BEC88984EE4EBEF643C79C8E0346@zammad.example.com',
               'Content-Description' => 'Rechnung_RE-2018-200.pdf',
               'Content-Disposition' => 'attachment',
             })

      params = {
        form_id: 'b47ea422-1b96-49db-8399-aeffaa0e3fc9',
      }
      authenticated_as(agent)
      post "/api/v1/ticket_attachment_upload_clone_by_article/#{article.id}", params: params, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['attachments']).to be_truthy
      expect(json_response['attachments'].count).to eq(3)

      post "/api/v1/ticket_attachment_upload_clone_by_article/#{article.id}", params: params, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['attachments']).to be_truthy
      expect(json_response['attachments'].count).to eq(0)
    end

    it 'does ticket split with plain - check attachments' do
      ticket = create(
        :ticket,
        group:         group,
        updated_by_id: agent.id,
        created_by_id: agent.id,
      )
      article = create(
        :ticket_article,
        ticket_id:     ticket.id,
        type:          Ticket::Article::Type.lookup(name: 'note'),
        sender:        Ticket::Article::Sender.lookup(name: 'Customer'),
        body:          '<b>test</b> <img src="cid:15.274327094.140938@zammad.example.com"/>',
        content_type:  'text/plain',
        updated_by_id: 1,
        created_by_id: 1,
      )
      create(:store,
             object:      'Ticket::Article',
             o_id:        article.id,
             data:        'content_file1_normally_should_be_an_image',
             filename:    'some_file1.jpg',
             preferences: {
               'Content-Type'        => 'image/jpeg',
               'Mime-Type'           => 'image/jpeg',
               'Content-ID'          => '15.274327094.140938@zammad.example.com',
               'Content-Disposition' => 'inline',
             })
      create(:store,
             object:      'Ticket::Article',
             o_id:        article.id,
             data:        'content_file1_normally_should_be_an_image',
             filename:    'some_file2.jpg',
             preferences: {
               'Content-Type'        => 'image/jpeg',
               'Mime-Type'           => 'image/jpeg',
               'Content-ID'          => '15.274327094.140938.2@zammad.example.com',
               'Content-Disposition' => 'inline',
             })
      create(:store,
             object:      'Ticket::Article',
             o_id:        article.id,
             data:        'content_file1_normally_should_be_an_pdf',
             filename:    'Rechnung_RE-2018-200.pdf',
             preferences: {
               'Content-Type'        => 'application/octet-stream; name="Rechnung_RE-2018-200.pdf"',
               'Mime-Type'           => 'application/octet-stream',
               'Content-ID'          => '8AB0BEC88984EE4EBEF643C79C8E0346@zammad.example.com',
               'Content-Description' => 'Rechnung_RE-2018-200.pdf',
               'Content-Disposition' => 'attachment',
             })

      params = {
        form_id: 'b47ea422-1b96-49db-8399-aeffaa0e3fc9',
      }
      authenticated_as(agent)
      post "/api/v1/ticket_attachment_upload_clone_by_article/#{article.id}", params: params, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['attachments']).to be_truthy
      expect(json_response['attachments'].count).to eq(3)

      post "/api/v1/ticket_attachment_upload_clone_by_article/#{article.id}", params: params, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['attachments']).to be_truthy
      expect(json_response['attachments'].count).to eq(0)
    end

    it 'does ticket create with mentions' do
      params = {
        title:       'a new ticket #1',
        group:       'Users',
        customer_id: customer.id,
        article:     {
          body: "some body <a data-mention-user-id=\"#{agent.id}\">agent</a>",
        }
      }
      authenticated_as(agent)
      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:created)
      expect(Mention.where(mentionable: Ticket.last).count).to eq(1)
    end

    it 'does not ticket create with invalid mentions' do
      params = {
        title:       'a new ticket #1',
        group:       'Users',
        customer_id: customer.id,
        article:     {
          body: "some body <a data-mention-user-id=\"#{create(:customer).id}\">customer</a>",
        }
      }
      authenticated_as(agent)
      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:unprocessable_content)
      expect(Mention.count).to eq(0)
    end

    it 'does not ticket create with mentions when customer' do
      params = {
        title:       'a new ticket #1',
        group:       'Users',
        customer_id: customer.id,
        article:     {
          body: "some body <a data-mention-user-id=\"#{agent.id}\">agent</a>",
        }
      }
      authenticated_as(customer)
      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:forbidden)
      expect(Mention.count).to eq(0)
    end

    context 'when special params should be updated' do
      it 'does not update created_at via PUT when import mode is inactive' do
        ticket  = create(:ticket, group: group)
        article = create(:ticket_article, ticket: ticket)

        original_created_at = article.created_at

        authenticated_as(agent)

        put "/api/v1/ticket_articles/#{article.id}", params: { created_at: 2.days.ago }, as: :json

        expect(response).to have_http_status(:ok)
        expect(article.reload.created_at.to_i).to eq(original_created_at.to_i)
      end

      it 'updates created_at via PUT when import mode is active' do
        ticket  = create(:ticket, group: group)
        article = create(:ticket_article, ticket: ticket)

        Setting.set('import_mode', true)
        authenticated_as(admin)

        new_created_at = Time.zone.parse('2020-01-02 03:04:05 UTC')

        put "/api/v1/ticket_articles/#{article.id}", params: { created_at: new_created_at }, as: :json

        expect(response).to have_http_status(:ok)
        expect(article.reload.created_at.to_i).to eq(new_created_at.to_i)
      end
    end
  end

  describe 'DELETE /api/v1/ticket_articles/:id', authenticated_as: -> { user } do
    let(:other_agent) { create(:agent, groups: [Group.first]) }

    let(:ticket) do
      create(:ticket, group: Group.first)
    end

    let(:article_note_self) do
      create(:ticket_article,
             sender_name: 'Agent', internal: true, type_name: 'note', ticket: ticket,
             updated_by_id: user.id, created_by_id: user.id)
    end

    let(:article_note_other) do
      create(:ticket_article,
             sender_name: 'Agent', internal: true, type_name: 'note', ticket: ticket,
             updated_by_id: other_agent.id, created_by_id: other_agent.id)
    end

    let(:article_note_customer) do
      create(:ticket_article,
             sender_name: 'Customer', internal: false, type_name: 'note', ticket: ticket,
             updated_by_id: customer.id, created_by_id: customer.id)
    end

    def delete_article_via_rest(article)
      delete "/api/v1/ticket_articles/#{article.id}", params: {}, as: :json
    end

    context 'as agent' do
      let(:user) { agent }

      it 'deletes an own internal note', :aggregate_failures do
        delete_article_via_rest(article_note_self)

        expect(response).to have_http_status(:ok)
        expect(article_note_self).not_to exist_in_database
      end

      it 'keeps the note of another agent', :aggregate_failures do
        delete_article_via_rest(article_note_other)

        expect(response).to have_http_status(:forbidden)
        expect(article_note_other).to exist_in_database
      end

      context 'with a custom delete timeframe' do
        before { Setting.set('ui_ticket_zoom_article_delete_timeframe', 6000) }

        it 'deletes an own internal note within the timeframe', :aggregate_failures do
          article_note_self
          travel 5000.seconds
          delete_article_via_rest(article_note_self)

          expect(response).to have_http_status(:ok)
          expect(article_note_self).not_to exist_in_database
        end

        it 'keeps an own internal note after the timeframe', :aggregate_failures do
          article_note_self
          travel 8000.seconds
          delete_article_via_rest(article_note_self)

          expect(response).to have_http_status(:forbidden)
          expect(article_note_self).to exist_in_database
        end
      end

      context 'without a delete timeframe' do
        before { Setting.set('ui_ticket_zoom_article_delete_timeframe', 0) }

        it 'deletes an old own internal note', :aggregate_failures do
          article_note_self
          travel 99.days
          delete_article_via_rest(article_note_self)

          expect(response).to have_http_status(:ok)
          expect(article_note_self).not_to exist_in_database
        end
      end
    end

    context 'as customer' do
      let(:user) { customer }

      it 'keeps the article', :aggregate_failures do
        delete_article_via_rest(article_note_customer)

        expect(response).to have_http_status(:forbidden)
        expect(article_note_customer).to exist_in_database
      end
    end
  end

  describe 'GET /api/v1/ticket_articles/:id', authenticated_as: :agent do
    let(:ticket)  { create(:ticket, group: Group.first) }

    context 'when body_rendering_error is present' do
      let(:article) { create(:ticket_article, :outbound_email, ticket: ticket, body: HtmlSanitizer::UNPROCESSABLE_HTML_MSG) }

      it 'includes body_rendering_error: true in the response' do
        get "/api/v1/ticket_articles/#{article.id}", as: :json
        expect(response).to have_http_status(:ok)
        expect(json_response['body_rendering_error']).to be(true)
      end
    end

    context 'when body is normal content' do
      let(:article) { create(:ticket_article, :outbound_email, ticket: ticket) }

      it 'includes body_rendering_error: false in the response' do
        get "/api/v1/ticket_articles/#{article.id}", as: :json
        expect(response).to have_http_status(:ok)
        expect(json_response['body_rendering_error']).to be(false)
      end
    end
  end

  describe 'GET /api/v1/ticket_articles/by_ticket/:id', authenticated_as: :agent do
    let(:ticket)    { create(:ticket, group: Group.first) }
    let!(:articles) { create_list(:ticket_article, 2, ticket: ticket) }

    context 'when requesting a full response' do
      it 'includes assets of all articles', :aggregate_failures do
        get "/api/v1/ticket_articles/by_ticket/#{ticket.id}", params: { full: true }, as: :json

        expect(response).to have_http_status(:ok)
        expect(json_response['record_ids']).to eq(articles.map(&:id))
        expect(json_response['assets']['TicketArticle'].keys).to match_array(articles.map { |article| article.id.to_s })
      end
    end
  end

  describe 'GET article endpoints with a detected language' do
    let(:ticket)   { create(:ticket, group: Group.first, customer:) }
    let!(:article) { create(:ticket_article, ticket:, detected_language: 'de') }

    def article_payloads
      get "/api/v1/ticket_articles/#{article.id}", as: :json
      show = json_response

      get "/api/v1/ticket_articles/#{article.id}", params: { full: true }, as: :json
      show_full = json_response.dig('assets', 'TicketArticle', article.id.to_s)

      get "/api/v1/ticket_articles/by_ticket/#{ticket.id}", as: :json
      by_ticket = json_response.find { |item| item['id'] == article.id }

      get "/api/v1/ticket_articles/by_ticket/#{ticket.id}", params: { full: true }, as: :json
      by_ticket_full = json_response.dig('assets', 'TicketArticle', article.id.to_s)

      { show:, show_full:, by_ticket:, by_ticket_full: }
    end

    context 'with an agent', authenticated_as: :agent do
      it 'returns the detected language' do
        expect(article_payloads.transform_values { it['detected_language'] })
          .to eq(show: 'de', show_full: 'de', by_ticket: 'de', by_ticket_full: 'de')
      end
    end

    context 'with a customer', authenticated_as: :customer do
      it 'returns no detected language' do
        expect(article_payloads.transform_values { it.key?('detected_language') })
          .to eq(show: false, show_full: false, by_ticket: false, by_ticket_full: false)
      end
    end
  end

  describe 'GET /api/v1/ticket_article_plain/:id', authenticated_as: :agent do
    let(:ticket)  { create(:ticket, group: Group.first) }
    let(:article) { create(:ticket_article, ticket: ticket) }

    context 'when article has a raw copy present' do
      before do
        article.save_as_raw('This is a test article')

        get "/api/v1/ticket_article_plain/#{article.id}"
      end

      it 'returns the raw copy of the article' do
        expect(response.body).to eq('This is a test article')
        expect(response.headers['Content-Length']).to eq('This is a test article'.bytesize.to_s)
      end
    end

    context 'when article does not have a raw copy' do
      before do
        get "/api/v1/ticket_article_plain/#{article.id}"
      end

      it 'returns 404' do
        expect(response).to have_http_status(:not_found)
      end

      it 'returns a human readable error message' do
        expect(response.body).to include('This article does not have a raw copy available.')
      end
    end
  end

  describe 'POST /api/v1/ticket_articles', authenticated_as: :user do
    let(:group)  { create(:group) }
    let(:ticket) { create(:ticket, group:) }

    describe 'permissions' do
      let(:params) do
        {
          ticket_id:    ticket.id,
          content_type: 'text/plain', # or text/html
          body:         'some body',
          type:         'note',
        }
      end

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

        before { user.user_groups.create!(group: group, access:) if defined?(access) }

        context 'when agent has full access to the group' do
          let(:access) { :full }

          it 'creates a new article' do
            expect { post '/api/v1/ticket_articles', params: params, as: :json }
              .to change { ticket.articles.count }.by(1)
          end
        end

        context 'when agent has change access to the group' do
          let(:access) { :change }

          it 'creates a new article' do
            expect { post '/api/v1/ticket_articles', params: params, as: :json }
              .to change { ticket.articles.count }.by(1)
          end
        end

        context 'when agent has read access to the group' do
          let(:access) { :read }

          it 'does not create a new article' do
            expect { post '/api/v1/ticket_articles', params: params, as: :json }
              .not_to change { ticket.articles.count }
          end
        end

        context 'when agent has customer access to the ticket' do
          let(:ticket) { create(:ticket, customer: user, group:) }
          let(:user) { create(:customer) }

          it 'creates a new article' do
            expect { post '/api/v1/ticket_articles', params: params, as: :json }
              .to change { ticket.articles.count }.by(1)
          end
        end
      end

      context 'when user is customer' do
        let(:ticket) { create(:ticket, customer: user) }
        let(:user)   { create(:customer) }

        it 'creates a new article' do
          expect { post '/api/v1/ticket_articles', params: params, as: :json }
            .to change { ticket.articles.count }.by(1)
        end
      end
    end

    describe 'article preferences write filtering' do
      let(:preferences) do
        {
          links:    [{ url: 'javascript:alert(1)//', target: '_blank', name: 'x' }],
          security: { type: '<img src=x onerror=alert(1)>' },
        }
      end
      let(:params) do
        {
          ticket_id:   ticket.id,
          body:        'some body',
          type:        'note',
          preferences:,
        }
      end

      context 'when user is customer' do
        let(:ticket) { create(:ticket, customer: user, group:) }
        let(:user)   { create(:customer) }

        it 'drops the client-supplied preferences' do
          post '/api/v1/ticket_articles', params: params, as: :json
          expect(response).to have_http_status(:created)
          expect(ticket.articles.last.preferences).not_to include('links', 'security')
        end
      end

      context 'when user is agent' do
        let(:user) { create(:agent, groups: [group]) }

        it 'keeps the preferences' do
          post '/api/v1/ticket_articles', params: params, as: :json
          expect(response).to have_http_status(:created)
          expect(ticket.articles.last.preferences).to include('links', 'security')
        end
      end
    end

  end

  describe 'POST /api/v1/ticket_articles (full response)', authenticated_as: :customer do
    let(:victim_ticket) do
      create(:ticket, group: group, customer: agent, created_by_id: agent.id, updated_by_id: agent.id)
    end

    let(:victim_article) do
      create(:'ticket/article', :internal_note,
             ticket:        victim_ticket,
             body:          'SECRET_INTERNAL_CONTENT',
             created_by_id: agent.id,
             updated_by_id: agent.id)
    end

    let(:attacker_ticket) do
      create(:ticket, group: group, customer: customer, created_by_id: customer.id, updated_by_id: customer.id)
    end

    it 'renders the created article, ignoring a decoupled id parameter', :aggregate_failures do
      post "/api/v1/ticket_articles?full=true&id=#{victim_article.id}",
           params: { ticket_id: attacker_ticket.id, body: 'legit follow-up' },
           as:     :json

      created_article = attacker_ticket.articles.reload.last

      expect(response).to have_http_status(:created)
      expect(json_response['id']).to eq(created_article.id)
      expect(json_response['assets']['TicketArticle'].keys).to include(created_article.id.to_s)
      expect(json_response['assets']['TicketArticle'].keys).not_to include(victim_article.id.to_s)
      expect(json_response['assets']['Ticket'].keys).not_to include(victim_ticket.id.to_s)
      expect(response.body).not_to include('SECRET_INTERNAL_CONTENT')
    end
  end
end
