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

require 'rails_helper'

RSpec.describe 'Ticket', type: :request do

  let!(:ticket_group) do
    create(:group, email_address: create(:email_address))
  end
  let!(:ticket_group_without_create) do
    create(:group, email_address: create(:email_address))
  end
  let(:admin) do
    create(:admin, groups: Group.all, firstname: 'Tickets', lastname: 'Admin')
  end
  let!(:agent) do
    create(:agent, groups: Group.all, firstname: 'Tickets', lastname: 'Agent')
  end
  let!(:agent_change_only) do
    user = create(:agent, groups: Group.all, firstname: 'Tickets', lastname: 'AgentChangeOnly')
    user.group_names_access_map = {
      ticket_group_without_create.name => %w[read change],
    }
    user
  end
  let!(:customer) do
    create(
      :customer,
      login:     'tickets-customer1@example.com',
      firstname: 'Tickets',
      lastname:  'Customer1',
      email:     'tickets-customer1@example.com',
    )
  end

  describe 'request handling' do

    it 'does ticket create with agent - missing group (01.01)' do
      params = {
        title:   'a new ticket #1',
        article: {
          content_type: 'text/plain', # or text/html
          body:         'some body',
          sender:       'Customer',
          type:         'note',
        },
      }
      authenticated_as(agent)
      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:unprocessable_content)
      expect(json_response).to be_a(Hash)
      expect(json_response['error_human']).to eq("The required value 'group_id' is missing.")
    end

    it 'does ticket create with agent - wrong group (01.02)' do
      params = {
        title:   'a new ticket #2',
        group:   'not_existing',
        article: {
          content_type: 'text/plain', # or text/html
          body:         'some body',
          sender:       'Customer',
          type:         'note',
        },
      }
      authenticated_as(agent)
      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:unprocessable_content)
      expect(json_response).to be_a(Hash)
      expect(json_response['error']).to eq('No lookup value found for \'group\': "not_existing"')
    end

    it 'does ticket create with agent - valid group but no create permissions (01.02a)' do
      params = {
        title:       'a new ticket #1',
        group:       ticket_group_without_create.name,
        priority:    '2 normal',
        state:       'new',
        customer_id: customer.id,
        article:     {
          content_type: 'text/plain', # or text/html
          body:         'some body',
          sender:       'Customer',
          type:         'note',
        },
      }
      authenticated_as(agent_change_only)
      post '/api/v1/tickets', params: 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')
    end

    it 'does ticket create with agent - missing article.body (01.03)' do
      params = {
        title:       'a new ticket #3',
        group:       ticket_group.name,
        priority:    '2 normal',
        state:       'new',
        customer_id: customer.id,
        article:     {},
      }
      authenticated_as(agent)
      expect { post '/api/v1/tickets', params: params, as: :json }.not_to change(Ticket, :count)
      expect(response).to have_http_status(:unprocessable_content)
      expect(json_response).to be_a(Hash)
      expect(json_response['error']).to eq("Need at least an 'article body' field.")
    end

    it 'does ticket create with agent - article.body set to empty string (01.03)' do
      params = {
        title:       'a new ticket #3',
        group:       ticket_group.name,
        priority:    '2 normal',
        state:       'new',
        customer_id: customer.id,
        article:     { body: " \n " },
      }
      authenticated_as(agent)
      expect { post '/api/v1/tickets', params: params, as: :json }.not_to change(Ticket, :count)
      expect(response).to have_http_status(:unprocessable_content)
      expect(json_response).to be_a(Hash)
      expect(json_response['error']).to eq("Need at least an 'article body' field.")
    end

    it 'does ticket create with agent - missing article (01.03)' do
      params = {
        title:       'a new ticket #3',
        group:       ticket_group.name,
        priority:    '2 normal',
        state:       'new',
        customer_id: customer.id
      }
      authenticated_as(agent)
      expect { post '/api/v1/tickets', params: params, as: :json }.to change(Ticket, :count).by(1)
      expect(response).to have_http_status(:created)
      expect(json_response).to be_a(Hash)

      ticket = Ticket.find(json_response['id'])
      expect(ticket.articles).to be_empty
    end

    it 'does ticket create with agent - minimal article (01.03)' do
      params = {
        title:       'a new ticket #3',
        group:       ticket_group.name,
        priority:    '2 normal',
        state:       'new',
        customer_id: customer.id,
        article:     {
          body: 'some test 123',
        },
      }
      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #3')
      expect(json_response['customer_id']).to eq(customer.id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)
    end

    it 'does ticket create with agent - minimal article and customer.email (01.04)' do
      params = {
        title:    'a new ticket #3',
        group:    ticket_group.name,
        priority: '2 normal',
        state:    'new',
        customer: customer.email,
        article:  {
          body: 'some test 123',
        },
      }
      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #3')
      expect(json_response['customer_id']).to eq(customer.id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)
    end

    it 'does ticket create with agent - wrong owner_id - 0 (01.05)' do
      params = {
        title:       'a new ticket #4',
        group:       ticket_group.name,
        priority:    '2 normal',
        owner_id:    0,
        state:       'new',
        customer_id: customer.id,
        article:     {
          body: 'some test 123',
        },
      }
      authenticated_as(agent)
      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:unprocessable_content)
      expect(json_response).to be_a(Hash)
      expect(json_response['error']).to eq('Invalid value for param \'owner_id\': 0')
    end

    it 'does ticket create with agent - wrong owner_id - "" (01.06)' do
      params = {
        title:       'a new ticket #5',
        group:       ticket_group.name,
        priority:    '2 normal',
        owner_id:    '',
        state:       'new',
        customer_id: customer.id,
        article:     {
          body: 'some test 123',
        },
      }
      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #5')
      expect(json_response['customer_id']).to eq(customer.id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)
    end

    it 'does ticket create with agent - wrong owner_id - 99999 (01.07)' do
      params = {
        title:       'a new ticket #6',
        group:       ticket_group.name,
        priority:    '2 normal',
        owner_id:    99_999,
        state:       'new',
        customer_id: customer.id,
        article:     {
          body: 'some test 123',
        },
      }
      authenticated_as(agent)
      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:unprocessable_content)
      expect(json_response).to be_a(Hash)
      expect(json_response['error']).to eq('Invalid value for param \'owner_id\': 99999')
    end

    it 'does ticket create with agent - wrong owner_id - nil (01.08)' do
      params = {
        title:       'a new ticket #7',
        group:       ticket_group.name,
        priority:    '2 normal',
        owner_id:    nil,
        state:       'new',
        customer_id: customer.id,
        article:     {
          body: 'some test 123',
        },
      }
      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #7')
      expect(json_response['customer_id']).to eq(customer.id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)
    end

    it 'does ticket create with agent - minimal article with guess customer (01.09)' do
      params = {
        title:       'a new ticket #9',
        group:       ticket_group.name,
        priority:    '2 normal',
        state:       'new',
        customer_id: 'guess:some_new_customer@example.com',
        article:     {
          body: 'some test 123',
        },
      }
      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #9')
      expect(json_response['customer_id']).to eq(User.lookup(email: 'some_new_customer@example.com').id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)
    end

    it 'does ticket create with agent - minimal article with guess customer (01.10)' do
      params = {
        title:       'a new ticket #10',
        group:       ticket_group.name,
        customer_id: 'guess:some_new_customer@example.com',
        article:     {
          body: 'some test 123',
        },
      }
      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #10')
      expect(json_response['customer_id']).to eq(User.lookup(email: 'some_new_customer@example.com').id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)
    end

    it 'does ticket create with agent - minimal article with customer hash (01.11)' do
      params = {
        title:    'a new ticket #11',
        group:    ticket_group.name,
        customer: {
          firstname: 'some firstname',
          lastname:  'some lastname',
          email:     'some_new_customer@example.com',
        },
        article:  {
          body: 'some test 123',
        },
      }
      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #11')
      expect(json_response['customer_id']).to eq(User.lookup(email: 'some_new_customer@example.com').id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)
    end

    it 'does ticket create with agent - minimal article with customer hash with article.origin_by (01.11)' do
      params = {
        title:    'a new ticket #11.1',
        group:    ticket_group.name,
        customer: {
          firstname: 'some firstname',
          lastname:  'some lastname',
          email:     'some_new_customer@example.com',
        },
        article:  {
          body:      'some test 123',
          origin_by: 'some_new_customer@example.com',
        },
      }
      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #11.1')
      expect(json_response['customer_id']).to eq(User.lookup(email: 'some_new_customer@example.com').id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)
      ticket = Ticket.find(json_response['id'])
      article = ticket.articles.first
      expect(article.updated_by_id).to eq(agent.id)
      expect(article.created_by_id).to eq(agent.id)
      expect(article.origin_by_id).to eq(User.lookup(email: 'some_new_customer@example.com').id)
      expect(article.sender.name).to eq('Customer')
      expect(article.type.name).to eq('note')
      expect(article.from).to eq('some firstname some lastname')
    end

    it 'does ticket create with agent - minimal article with customer hash with article.origin_by (01.11) - second test' do
      params = {
        title:    'a new ticket #11.2',
        group:    ticket_group.name,
        customer: {
          firstname: 'some firstname',
          lastname:  'some lastname',
          email:     'some_new_customer@example.com',
        },
        article:  {
          sender:    'Customer',
          body:      'some test 123',
          origin_by: 'some_new_customer@example.com',
        },
      }
      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #11.2')
      expect(json_response['customer_id']).to eq(User.lookup(email: 'some_new_customer@example.com').id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)
      ticket = Ticket.find(json_response['id'])
      article = ticket.articles.first
      expect(article.updated_by_id).to eq(agent.id)
      expect(article.created_by_id).to eq(agent.id)
      expect(article.origin_by_id).to eq(User.lookup(email: 'some_new_customer@example.com').id)
      expect(article.sender.name).to eq('Customer')
      expect(article.type.name).to eq('note')
      expect(article.from).to eq('some firstname some lastname')
    end

    it 'does ticket create with agent - minimal article with customer hash with article.origin_by (01.11) - third test' do
      params = {
        title:    'a new ticket #11.3',
        group:    ticket_group.name,
        customer: {
          firstname: 'some firstname',
          lastname:  'some lastname',
          email:     'some_new_customer@example.com',
        },
        article:  {
          sender:    'Agent',
          from:      'somebody',
          body:      'some test 123',
          origin_by: 'some_new_customer@example.com',
        },
      }
      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #11.3')
      expect(json_response['customer_id']).to eq(User.lookup(email: 'some_new_customer@example.com').id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)
      ticket = Ticket.find(json_response['id'])
      article = ticket.articles.first
      expect(article.updated_by_id).to eq(agent.id)
      expect(article.created_by_id).to eq(agent.id)
      expect(article.origin_by_id).to eq(User.lookup(email: 'some_new_customer@example.com').id)
      expect(article.sender.name).to eq('Customer')
      expect(article.type.name).to eq('note')
      expect(article.from).to eq('some firstname some lastname')
    end

    it 'does ticket create with agent - minimal article with customer hash with article.origin_by (01.11) - fourth test' do
      params = {
        title:    'a new ticket #11.4',
        group:    ticket_group.name,
        customer: {
          firstname: 'some firstname',
          lastname:  'some lastname',
          email:     'some_new_customer@example.com',
        },
        article:  {
          sender:    'Customer',
          body:      'some test 123',
          origin_by: customer.login,
        },
      }
      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #11.4')
      expect(json_response['customer_id']).to eq(User.lookup(email: 'some_new_customer@example.com').id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)
      ticket = Ticket.find(json_response['id'])
      article = ticket.articles.first
      expect(article.updated_by_id).to eq(agent.id)
      expect(article.created_by_id).to eq(agent.id)
      expect(article.origin_by_id).to eq(customer.id)
      expect(article.sender.name).to eq('Customer')
      expect(article.type.name).to eq('note')
      expect(article.from).to eq('Tickets Customer1')
    end

    it 'does ticket create with agent - minimal article with missing body - with customer.id (01.12)' do
      params = {
        title:       'a new ticket #12',
        group:       ticket_group.name,
        customer_id: customer.id,
        article:     {
          subject: 'some test 123',
        },
      }
      authenticated_as(agent)
      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:unprocessable_content)
      expect(json_response).to be_a(Hash)
      expect(json_response['error']).to eq("Need at least an 'article body' field.")
    end

    it 'does ticket create with agent - minimal article and attachment with customer (01.13)' do
      params = {
        title:       'a new ticket #13',
        group:       ticket_group.name,
        customer_id: customer.id,
        article:     {
          subject:     'some test 123',
          body:        'some test 123',
          attachments: [
            { 'filename'  => 'some_file.txt',
              'data'      => 'dGVzdCAxMjM=',
              'mime-type' => 'text/plain' },
          ],
        },
      }
      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #13')
      expect(json_response['customer_id']).to eq(customer.id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)

      ticket = Ticket.find(json_response['id'])
      expect(ticket.articles.count).to eq(1)
      expect(ticket.articles.first.attachments.count).to eq(1)
      file = ticket.articles.first.attachments.first
      expect(file.content).to eq('test 123')
      expect(file.filename).to eq('some_file.txt')
      expect(file.preferences['Mime-Type']).to eq('text/plain')
      expect(file.preferences['Content-ID']).to be_falsey
    end

    it 'does ticket create with agent - minimal article and attachment with customer (01.14)' do
      params = {
        title:       'a new ticket #14',
        group:       ticket_group.name,
        customer_id: customer.id,
        article:     {
          subject:     'some test 123',
          body:        'some test 123',
          attachments: [
            {
              'filename'  => 'some_file1.txt',
              'data'      => 'dGVzdCAxMjM=',
              'mime-type' => 'text/plain',
            },
            {
              'filename'  => 'some_file2.txt',
              'data'      => 'w6TDtsO8w58=',
              'mime-type' => 'text/plain',
            },
          ],
        },
      }
      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #14')
      expect(json_response['customer_id']).to eq(customer.id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)

      ticket = Ticket.find(json_response['id'])
      expect(ticket.articles.count).to eq(1)
      expect(ticket.articles.first.attachments.count).to eq(2)
      file = ticket.articles.first.attachments.first
      expect(file.content).to eq('test 123')
      expect(file.filename).to eq('some_file1.txt')
      expect(file.preferences['Mime-Type']).to eq('text/plain')
      expect(file.preferences['Content-ID']).to be_falsey
    end

    it 'does ticket create with agent - minimal article and simple invalid base64 attachment with customer (01.15)' do
      params = {
        title:       'a new ticket #15',
        group:       ticket_group.name,
        customer_id: customer.id,
        article:     {
          subject:     'some test 123',
          body:        'some test 123',
          attachments: [
            { 'filename'  => 'some_file.txt',
              'data'      => 'ABC_INVALID_BASE64',
              'mime-type' => 'text/plain' },
          ],
        },
      }
      authenticated_as(agent)
      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:unprocessable_content)
      expect(json_response).to be_a(Hash)
      expect(json_response['error']).to eq('Invalid base64 for attachment with index \'0\'')
    end

    it 'does ticket create with agent - minimal article and large invalid base64 attachment with customer (01.15a)' do
      params = {
        title:       'a new ticket #15a',
        group:       ticket_group.name,
        customer_id: customer.id,
        article:     {
          subject:     'some test 123',
          body:        'some test 123',
          attachments: [
            { 'filename'  => 'some_file.txt',
              'data'      => "LARGE_INVALID_BASE64_#{'#' * 20_000_000}",
              'mime-type' => 'text/plain' },
          ],
        },
      }
      authenticated_as(agent)
      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:unprocessable_content)
      expect(json_response).to be_a(Hash)
      expect(json_response['error']).to eq('Invalid base64 for attachment with index \'0\'')
    end

    it 'does ticket create with agent - minimal article and valid multiline base64 with linebreaks attachment with customer (01.15b)' do
      params = {
        title:       'a new ticket #15b',
        group:       ticket_group.name,
        customer_id: customer.id,
        article:     {
          subject:     'some test 123',
          body:        'some test 123',
          attachments: [
            { 'filename'  => 'some_file.txt',
              'data'      => Base64.encode64('a' * 1_000),
              'mime-type' => 'text/plain' },
          ],
        },
      }
      authenticated_as(agent)
      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:created)
      expect(json_response['title']).to eq('a new ticket #15b')
      ticket = Ticket.find(json_response['id'])
      expect(ticket.articles.count).to eq(1)
      expect(ticket.articles.first.attachments.count).to eq(1)
      file = ticket.articles.first.attachments.first
      expect(file.content).to eq('a' * 1_000)
    end

    it 'does ticket create with agent - minimal article and valid multiline base64 without linebreaks attachment with customer (01.15c)' do
      params = {
        title:       'a new ticket #15c',
        group:       ticket_group.name,
        customer_id: customer.id,
        article:     {
          subject:     'some test 123',
          body:        'some test 123',
          attachments: [
            { 'filename'  => 'some_file.txt',
              'data'      => Base64.strict_encode64('a' * 1_000),
              'mime-type' => 'text/plain' },
          ],
        },
      }
      authenticated_as(agent)
      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:created)
      expect(json_response['title']).to eq('a new ticket #15c')
      ticket = Ticket.find(json_response['id'])
      expect(ticket.articles.count).to eq(1)
      expect(ticket.articles.first.attachments.count).to eq(1)
      file = ticket.articles.first.attachments.first
      expect(file.content).to eq('a' * 1_000)
    end

    it 'does ticket create with agent - minimal article and attachment invalid base64 with customer (01.16)' do
      params = {
        title:       'a new ticket #16',
        group:       ticket_group.name,
        customer_id: customer.id,
        article:     {
          subject:     'some test 123',
          body:        'some test 123',
          attachments: [
            { 'filename' => 'some_file.txt',
              'data'     => 'dGVzdCAxMjM=' },
          ],
        },
      }
      authenticated_as(agent)
      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:unprocessable_content)
      expect(json_response).to be_a(Hash)
      expect(json_response['error']).to eq('Attachment needs \'mime-type\' param for attachment with index \'0\'')
    end

    it 'does ticket create with agent - minimal article and inline attachments with customer (01.17)' do
      params = {
        title:       'a new ticket #17',
        group:       ticket_group.name,
        customer_id: customer.id,
        article:     {
          content_type: 'text/html',
          subject:      'some test 123',
          body:         'some test 123 <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
  AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
  9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" /> <img src="data:image/jpeg;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAAJAAD/4QMtaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjMtYzAxMSA2Ni4xNDU2NjEsIDIwMTIvMDIvMDYtMTQ6NTY6MjcgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDUzYgKE1hY2ludG9zaCkiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6QzJCOTE2NzlGQUEwMTFFNjg0M0NGQjU0OUU4MTFEOEIiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6QzJCOTE2N0FGQUEwMTFFNjg0M0NGQjU0OUU4MTFEOEIiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpDMkI5MTY3N0ZBQTAxMUU2ODQzQ0ZCNTQ5RTgxMUQ4QiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpDMkI5MTY3OEZBQTAxMUU2ODQzQ0ZCNTQ5RTgxMUQ4QiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pv/uAA5BZG9iZQBkwAAAAAH/2wCEABQRERoTGioZGSo1KCEoNTEpKCgpMUE4ODg4OEFEREREREREREREREREREREREREREREREREREREREREREREREQBFhoaIh0iKRoaKTkpIik5RDktLTlEREREOERERERERERERERERERERERERERERERERERERERERERERERERERERP/AABEIABAADAMBIgACEQEDEQH/xABbAAEBAAAAAAAAAAAAAAAAAAAEBQEBAQAAAAAAAAAAAAAAAAAABAUQAAEEAgMAAAAAAAAAAAAAAAABAhIDESIxBAURAAICAwAAAAAAAAAAAAAAAAESABNRoQP/2gAMAwEAAhEDEQA/AJDq1rfF3Imeg/1+lFy2oR564DKWWWbweV+Buf/Z">',
        },
      }
      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #17')
      expect(json_response['customer_id']).to eq(customer.id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)

      ticket = Ticket.find(json_response['id'])
      expect(ticket.articles.count).to eq(1)
      expect(ticket.articles.first.attachments.count).to eq(2)
      file = ticket.articles.first.attachments[0]
      expect(Digest::MD5.hexdigest(file.content)).to eq('d3c1e09bdefb92b6a06b791a24ca9599')
      expect(file.filename).to eq('image1.png')
      expect(file.preferences['Mime-Type']).to eq('image/png')
      expect(file.preferences['Content-ID']).to match(%r{#{ticket.id}\..+?@zammad.example.com})
      expect(file.preferences['Content-ID']).to be_truthy
      file = ticket.articles.first.attachments[1]
      expect(Digest::MD5.hexdigest(file.content)).to eq('006a2ca3793b550c8fe444acdeb39252')
      expect(file.filename).to eq('image2.jpeg')
      expect(file.preferences['Mime-Type']).to eq('image/jpeg')
      expect(file.preferences['Content-ID']).to match(%r{#{ticket.id}\..+?@zammad.example.com})
      expect(file.preferences['Content-ID']).to be_truthy
    end

    it 'does ticket create with agent - minimal article and inline attachments with customer (01.18)' do
      params = {
        title:       'a new ticket #18',
        group:       ticket_group.name,
        customer_id: customer.id,
        article:     {
          content_type: 'text/html',
          subject:      'some test 123',
          body:         'some test 123 <img src="data:image/jpeg;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAAJAAD/4QMtaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjMtYzAxMSA2Ni4xNDU2NjEsIDIwMTIvMDIvMDYtMTQ6NTY6MjcgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDUzYgKE1hY2ludG9zaCkiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6QzJCOTE2NzlGQUEwMTFFNjg0M0NGQjU0OUU4MTFEOEIiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6QzJCOTE2N0FGQUEwMTFFNjg0M0NGQjU0OUU4MTFEOEIiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpDMkI5MTY3N0ZBQTAxMUU2ODQzQ0ZCNTQ5RTgxMUQ4QiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpDMkI5MTY3OEZBQTAxMUU2ODQzQ0ZCNTQ5RTgxMUQ4QiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pv/uAA5BZG9iZQBkwAAAAAH/2wCEABQRERoTGioZGSo1KCEoNTEpKCgpMUE4ODg4OEFEREREREREREREREREREREREREREREREREREREREREREREREQBFhoaIh0iKRoaKTkpIik5RDktLTlEREREOERERERERERERERERERERERERERERERERERERERERERERERERERERP/AABEIABAADAMBIgACEQEDEQH/xABbAAEBAAAAAAAAAAAAAAAAAAAEBQEBAQAAAAAAAAAAAAAAAAAABAUQAAEEAgMAAAAAAAAAAAAAAAABAhIDESIxBAURAAICAwAAAAAAAAAAAAAAAAESABNRoQP/2gAMAwEAAhEDEQA/AJDq1rfF3Imeg/1+lFy2oR564DKWWWbweV+Buf/Z"
  >',
          attachments:  [
            { 'filename'  => 'some_file.txt',
              'data'      => 'dGVzdCAxMjM=',
              'mime-type' => 'text/plain' },
          ],
        },
      }
      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #18')
      expect(json_response['customer_id']).to eq(customer.id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)

      ticket = Ticket.find(json_response['id'])

      expect(ticket.articles.count).to eq(1)
      expect(ticket.articles.first.attachments.count).to eq(2)
      file = ticket.articles.first.attachments[0]
      expect(Digest::MD5.hexdigest(file.content)).to eq('006a2ca3793b550c8fe444acdeb39252')
      expect(file.filename).to eq('image1.jpeg')
      expect(file.preferences['Mime-Type']).to eq('image/jpeg')
      expect(file.preferences['Content-ID']).to be_truthy
      expect(file.preferences['Content-ID']).to match(%r{#{ticket.id}\..+?@zammad.example.com})
      expect(file).to be_inline
      file = ticket.articles.first.attachments[1]
      expect(Digest::MD5.hexdigest(file.content)).to eq('39d0d586a701e199389d954f2d592720')
      expect(file.filename).to eq('some_file.txt')
      expect(file.preferences['Mime-Type']).to eq('text/plain')
      expect(file.preferences['Content-ID']).to be_falsey
      expect(file).not_to be_inline
    end

    it 'does ticket create with agent (02.02)' do
      target_ticket = create(:ticket, group: ticket_group)
      params = {
        title:    'a new ticket #1',
        state:    'new',
        priority: '2 normal',
        group:    ticket_group.name,
        customer: 'tickets-customer1@example.com',
        article:  {
          content_type: 'text/plain', # or text/html
          body:         'some body',
        },
        links:    {
          Ticket: {
            parent: [target_ticket.id],
          }
        }
      }
      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #1')
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)
      links = Link.list(
        link_object:       'Ticket',
        link_object_value: json_response['id'],
      )
      expect(links[0]['link_type']).to eq('child')
      expect(links[0]['link_object']).to eq('Ticket')
      expect(links[0]['link_object_value']).to eq(target_ticket.id)
    end

    it 'does ticket with wrong ticket id (02.03)' do
      group = create(:group)
      ticket = create(
        :ticket,
        title:       'ticket with wrong ticket id',
        group_id:    group.id,
        customer_id: customer.id,
      )
      authenticated_as(agent)
      get "/api/v1/tickets/#{ticket.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')

      params = {
        title: 'ticket with wrong ticket id - 2',
      }
      put "/api/v1/tickets/#{ticket.id}", params: 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')

      delete "/api/v1/tickets/#{ticket.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')
    end

    context 'with an agent working on a ticket (02.04)' do
      let(:title)  { "ticket with corret ticket id testagent#{SecureRandom.uuid}" }
      let(:ticket) { create(:ticket, title:, group: ticket_group, customer_id: customer.id, preferences: { some_key1: 123 }) }

      before { authenticated_as(agent) }

      def create_article(**params)
        post '/api/v1/ticket_articles', params: { ticket_id: ticket.id, subject: 'some subject', body: 'some body' }.merge(params), as: :json
        expect(response).to have_http_status(:created)
        json_response
      end

      it 'shows the ticket' do
        get "/api/v1/tickets/#{ticket.id}", params: {}, as: :json

        expect(json_response).to include(
          'id' => ticket.id, 'title' => title, 'customer_id' => customer.id,
          'updated_by_id' => 1, 'created_by_id' => 1, 'preferences' => include('some_key1' => 123)
        )
      end

      it 'updates title, customer and preferences, keeping existing preferences' do
        put "/api/v1/tickets/#{ticket.id}", params: { title: "#{title} - 2", customer_id: agent.id, preferences: { some_key2: 'abc' } }, as: :json

        expect(json_response).to include(
          'title' => "#{title} - 2", 'customer_id' => agent.id, 'updated_by_id' => agent.id, 'created_by_id' => 1,
          'preferences' => include('some_key1' => 123, 'some_key2' => 'abc')
        )
      end

      it 'creates a note as agent' do
        expect(create_article).to include(
          'ticket_id' => ticket.id, 'from' => 'Tickets Agent', 'subject' => 'some subject', 'body' => 'some body',
          'content_type' => 'text/plain', 'internal' => false, 'created_by_id' => agent.id,
          'sender_id' => Ticket::Article::Sender.lookup(name: 'Agent').id, 'type_id' => Ticket::Article::Type.lookup(name: 'note').id
        )
      end

      it 'finds the ticket by query and by condition', :aggregate_failures, performs_jobs: true do
        # The database search fallback only finds tickets with articles.
        create(:ticket_article, ticket:)
        perform_enqueued_jobs

        get "/api/v1/tickets/search?query=#{CGI.escape(title)}&full=true", params: {}, as: :json
        expect(json_response['record_ids']).to eq([ticket.id])

        post '/api/v1/tickets/search?full=true', params: { condition: { 'ticket.title' => { operator: 'contains', value: title } } }, as: :json
        expect(json_response['record_ids']).to eq([ticket.id])
      end

      it 'creates an email with the server side sender and keeps its subject', :aggregate_failures do
        email = create_article(to: Faker::Internet.unique.email, from: 'something which should not be changed on server side', type: 'email', internal: true)

        expect(email).to include(
          'from' => %(Tickets Agent via #{ticket_group.email_address.name} <#{ticket_group.email_address.email}>),
          'internal' => true, 'type_id' => Ticket::Article::Type.lookup(name: 'email').id
        )

        put "/api/v1/ticket_articles/#{email['id']}", params: { subject: 'new subject' }, as: :json
        expect(response).to have_http_status(:ok)
        expect(Ticket::Article.find(email['id']).subject).to eq('some subject')
      end

      it 'does not delete a public email', :aggregate_failures do
        email = create_article(to: Faker::Internet.unique.email, type: 'email', internal: false)

        delete "/api/v1/ticket_articles/#{email['id']}", params: {}, as: :json
        expect(response).to have_http_status(:forbidden)
        expect(json_response['error']).to eq('Not authorized (communication articles cannot be deleted)!')
        expect(Ticket::Article).to exist(email['id'])
      end

      it 'does not delete the ticket', :aggregate_failures do
        delete "/api/v1/tickets/#{ticket.id}", params: {}, as: :json

        expect(response).to have_http_status(:forbidden)
        expect(json_response['error']).to eq('Not authorized (admin permission required)!')
        expect(ticket).to exist_in_database
      end
    end

    it 'does ticket with correct ticket id (02.05)' do
      ticket = create(
        :ticket,
        title:       'ticket with corret ticket id',
        group:       ticket_group,
        customer_id: customer.id,
      )
      authenticated_as(admin)
      get "/api/v1/tickets/#{ticket.id}", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['id']).to eq(ticket.id)
      expect(json_response['title']).to eq('ticket with corret ticket id')
      expect(json_response['customer_id']).to eq(ticket.customer_id)
      expect(json_response['updated_by_id']).to eq(1)
      expect(json_response['created_by_id']).to eq(1)

      params = {
        title:       'ticket with corret ticket id - 2',
        customer_id: agent.id,
      }
      put "/api/v1/tickets/#{ticket.id}", params: params, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['id']).to eq(ticket.id)
      expect(json_response['title']).to eq('ticket with corret ticket id - 2')
      expect(json_response['customer_id']).to eq(agent.id)
      expect(json_response['updated_by_id']).to eq(admin.id)
      expect(json_response['created_by_id']).to eq(1)

      params = {
        from:      'something which should not be changed on server side',
        ticket_id: ticket.id,
        subject:   'some subject',
        body:      'some body',
      }
      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['ticket_id']).to eq(ticket.id)
      expect(json_response['from']).to eq('Tickets Admin')
      expect(json_response['subject']).to eq('some subject')
      expect(json_response['body']).to eq('some body')
      expect(json_response['content_type']).to eq('text/plain')
      expect(json_response['internal']).to be(false)
      expect(json_response['created_by_id']).to eq(admin.id)
      expect(json_response['sender_id']).to eq(Ticket::Article::Sender.lookup(name: 'Agent').id)
      expect(json_response['type_id']).to eq(Ticket::Article::Type.lookup(name: 'note').id)

      params = {
        subject:  'new subject',
        internal: true,
      }
      put "/api/v1/ticket_articles/#{json_response['id']}", params: params, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['ticket_id']).to eq(ticket.id)
      expect(json_response['from']).to eq('Tickets Admin')
      expect(json_response['subject']).not_to eq('new subject')
      expect(json_response['body']).to eq('some body')
      expect(json_response['content_type']).to eq('text/plain')
      expect(json_response['internal']).to be(true)
      expect(json_response['created_by_id']).to eq(admin.id)
      expect(json_response['sender_id']).to eq(Ticket::Article::Sender.lookup(name: 'Agent').id)
      expect(json_response['type_id']).to eq(Ticket::Article::Type.lookup(name: 'note').id)

      delete "/api/v1/ticket_articles/#{json_response['id']}", params: {}, as: :json
      expect(response).to have_http_status(:ok)

      params = {
        ticket_id: ticket.id,
        subject:   'some subject',
        body:      'some body',
        type:      'email',
        to:        Faker::Internet.unique.email,
      }
      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['ticket_id']).to eq(ticket.id)
      expect(json_response['from']).to eq(%(Tickets Admin via #{ticket_group.email_address.name} <#{ticket_group.email_address.email}>))
      expect(json_response['subject']).to eq('some subject')
      expect(json_response['body']).to eq('some body')
      expect(json_response['content_type']).to eq('text/plain')
      expect(json_response['internal']).to be(false)
      expect(json_response['created_by_id']).to eq(admin.id)
      expect(json_response['sender_id']).to eq(Ticket::Article::Sender.lookup(name: 'Agent').id)
      expect(json_response['type_id']).to eq(Ticket::Article::Type.lookup(name: 'email').id)

      delete "/api/v1/ticket_articles/#{json_response['id']}", params: {}, as: :json
      expect(response).to have_http_status(:forbidden)

      delete "/api/v1/tickets/#{ticket.id}", params: {}, as: :json
      expect(response).to have_http_status(:ok)
    end

    it 'does ticket pagination (02.05)' do
      title = "ticket pagination #{SecureRandom.uuid}"
      tickets = []
      (1..20).each do |count|
        ticket = create(
          :ticket,
          title:       "#{title} - #{count}",
          group:       ticket_group,
          customer_id: customer.id,
        )
        create(
          :ticket_article,
          type:      Ticket::Article::Type.lookup(name: 'note'),
          sender:    Ticket::Article::Sender.lookup(name: 'Customer'),
          ticket_id: ticket.id,
        )
        tickets.push ticket
        travel 2.seconds
      end

      authenticated_as(admin)
      get "/api/v1/tickets/search?query=#{CGI.escape(title)}&limit=40&full=true", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['record_ids'][0]).to eq(tickets[19].id)
      expect(json_response['record_ids'][19]).to eq(tickets[0].id)
      expect(json_response['record_ids'].count).to eq(20)

      get "/api/v1/tickets/search?query=#{CGI.escape(title)}&limit=10&full=true", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['record_ids'][0]).to eq(tickets[19].id)
      expect(json_response['record_ids'][9]).to eq(tickets[10].id)
      expect(json_response['record_ids'].count).to eq(10)

      get "/api/v1/tickets/search?query=#{CGI.escape(title)}&limit=40&full=true&page=1&per_page=5", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['record_ids'][0]).to eq(tickets[19].id)
      expect(json_response['record_ids'][4]).to eq(tickets[15].id)
      expect(json_response['record_ids'].count).to eq(5)

      get "/api/v1/tickets/search?query=#{CGI.escape(title)}&limit=40&full=true&page=2&per_page=5", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['record_ids'][0]).to eq(tickets[14].id)
      expect(json_response['record_ids'][4]).to eq(tickets[10].id)
      expect(json_response['record_ids'].count).to eq(5)

      get '/api/v1/tickets?limit=40&page=1&per_page=5', params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Array)
      tickets = Ticket.reorder(:id).limit(5)
      expect(json_response[0]['id']).to eq(tickets[0].id)
      expect(json_response[4]['id']).to eq(tickets[4].id)
      expect(json_response.count).to eq(5)

      get '/api/v1/tickets?limit=40&page=2&per_page=5', params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Array)
      tickets = Ticket.reorder(:id).limit(10)
      expect(json_response[0]['id']).to eq(tickets[5].id)
      expect(json_response[4]['id']).to eq(tickets[9].id)
      expect(json_response.count).to eq(5)

    end

    it 'does ticket create with customer minimal (03.01)' do
      params = {
        title:    'a new ticket #c1',
        state:    'new',
        priority: '2 normal',
        group:    ticket_group.name,
        article:  {
          body: 'some body',
        },
      }
      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(json_response['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #c1')
      expect(json_response['customer_id']).to eq(customer.id)
      expect(json_response['updated_by_id']).to eq(customer.id)
      expect(json_response['created_by_id']).to eq(customer.id)
    end

    it 'does ticket create with customer with wrong customer (03.02)' do
      params = {
        title:       'a new ticket #c2',
        state:       'new',
        priority:    '2 normal',
        group:       ticket_group.name,
        customer_id: agent.id,
        article:     {
          content_type: 'text/plain', # or text/html
          body:         'some body',
          sender:       'System',
        },
      }
      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(json_response['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #c2')
      expect(json_response['customer_id']).to eq(customer.id)
      expect(json_response['updated_by_id']).to eq(customer.id)
      expect(json_response['created_by_id']).to eq(customer.id)
    end

    it 'does ticket create with customer with wrong customer hash (03.03)' do
      params = {
        title:    'a new ticket #c2',
        state:    'new',
        priority: '2 normal',
        group:    ticket_group.name,
        customer: {
          firstname: agent.firstname,
          lastname:  agent.lastname,
          email:     agent.email,
        },
        article:  {
          content_type: 'text/plain', # or text/html
          body:         'some body',
          sender:       'System',
        },
      }
      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(json_response['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #c2')
      expect(json_response['customer_id']).to eq(customer.id)
      expect(json_response['updated_by_id']).to eq(customer.id)
      expect(json_response['created_by_id']).to eq(customer.id)
    end

    it 'does ticket with wrong ticket id (03.04)' do
      ticket = create(
        :ticket,
        title:       'ticket with wrong ticket id',
        group:       ticket_group,
        customer_id: agent.id,
      )
      authenticated_as(customer)
      get "/api/v1/tickets/#{ticket.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')

      params = {
        title: 'ticket with wrong ticket id - 2',
      }
      put "/api/v1/tickets/#{ticket.id}", params: 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')

      delete "/api/v1/tickets/#{ticket.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')
    end

    context 'with a customer working on a ticket (03.05)' do
      let(:title)  { "ticket with corret ticket id testme#{SecureRandom.uuid}" }
      let(:ticket) { create(:ticket, title:, group: ticket_group, customer_id: customer.id) }

      before { authenticated_as(customer) }

      def create_article(**params)
        post '/api/v1/ticket_articles', params: { ticket_id: ticket.id, subject: 'some subject', body: 'some body' }.merge(params), as: :json
        expect(response).to have_http_status(:created)
        json_response
      end

      it 'shows the ticket' do
        get "/api/v1/tickets/#{ticket.id}", params: {}, as: :json

        expect(json_response).to include('id' => ticket.id, 'title' => title, 'customer_id' => customer.id)
      end

      it 'updates the title but not the customer' do
        put "/api/v1/tickets/#{ticket.id}", params: { title: "#{title} - 2", customer_id: agent.id }, as: :json

        expect(json_response).to include('title' => "#{title} - 2", 'customer_id' => customer.id, 'updated_by_id' => customer.id)
      end

      it 'creates a note as customer' do
        expect(create_article).to include(
          'from' => 'Tickets Customer1', 'created_by_id' => customer.id,
          'sender_id' => Ticket::Article::Sender.lookup(name: 'Customer').id, 'type_id' => Ticket::Article::Type.lookup(name: 'note').id
        )
      end

      it 'turns a requested agent email into a customer note' do
        expect(create_article(type: 'email', sender: 'Agent')).to include(
          'from' => 'Tickets Customer1',
          'sender_id' => Ticket::Article::Sender.lookup(name: 'Customer').id, 'type_id' => Ticket::Article::Type.lookup(name: 'note').id
        )
      end

      it 'turns a requested internal agent web article into a public customer one' do
        expect(create_article(from: 'something which should not be changed on server side', type: 'web', sender: 'Agent', internal: true)).to include(
          'from' => 'Tickets Customer1 <tickets-customer1@example.com>', 'internal' => false,
          'sender_id' => Ticket::Article::Sender.lookup(name: 'Customer').id, 'type_id' => Ticket::Article::Type.lookup(name: 'web').id
        )
      end

      it 'finds the ticket by query and by condition', :aggregate_failures, performs_jobs: true do
        # The database search fallback only finds tickets with articles.
        create(:ticket_article, ticket:)
        perform_enqueued_jobs

        get "/api/v1/tickets/search?query=#{CGI.escape(title)}&full=true", params: {}, as: :json
        expect(json_response['record_ids']).to eq([ticket.id])

        post '/api/v1/tickets/search?full=true', params: { condition: { 'ticket.title' => { operator: 'contains', value: title } } }, as: :json
        expect(json_response['record_ids']).to eq([ticket.id])
      end

      it 'does not change or delete articles', :aggregate_failures do
        article = create_article

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

        delete "/api/v1/ticket_articles/#{article['id']}", params: {}, as: :json
        expect(response).to have_http_status(:forbidden)
        expect(json_response['error']).to eq('Not authorized (agent permission required)!')
        expect(Ticket::Article).to exist(article['id'])
      end

      it 'does not delete the ticket', :aggregate_failures do
        delete "/api/v1/tickets/#{ticket.id}", params: {}, as: :json

        expect(response).to have_http_status(:forbidden)
        expect(json_response['error']).to eq('Not authorized (admin permission required)!')
        expect(ticket).to exist_in_database
      end
    end

    it 'does ticket create with agent - minimal article with customer hash with article.origin_by (03.6)' do
      authenticated_as(customer)
      params = {
        title:    'a new ticket #3.6',
        group:    ticket_group.name,
        customer: {
          firstname: 'some firstname',
          lastname:  'some lastname',
          email:     'some_new_customer@example.com',
        },
        article:  {
          body:      'some test 123',
          origin_by: agent.login,
        },
      }

      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #3.6')
      expect(json_response['customer_id']).to eq(customer.id)
      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['id'])
      article = ticket.articles.first
      expect(article.updated_by_id).to eq(customer.id)
      expect(article.created_by_id).to eq(customer.id)
      expect(article.origin_by_id).to eq(customer.id)
      expect(article.sender.name).to eq('Customer')
      expect(article.type.name).to eq('note')
      expect(article.from).to eq('Tickets Customer1')
    end

    it 'does ticket create with agent - minimal article with customer hash with article.origin_by (03.6) - second test' do
      authenticated_as(customer)
      params = {
        title:    'a new ticket #3.6.1',
        group:    ticket_group.name,
        customer: {
          firstname: 'some firstname',
          lastname:  'some lastname',
          email:     'some_new_customer@example.com',
        },
        article:  {
          sender:       'Agent',
          body:         'some test 123',
          origin_by_id: agent.id,
        },
      }

      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['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq('a new ticket #3.6.1')
      expect(json_response['customer_id']).to eq(customer.id)
      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['id'])
      article = ticket.articles.first
      expect(article.updated_by_id).to eq(customer.id)
      expect(article.created_by_id).to eq(customer.id)
      expect(article.origin_by_id).to eq(customer.id)
      expect(article.sender.name).to eq('Customer')
      expect(article.type.name).to eq('note')
      expect(article.from).to eq('Tickets Customer1')
    end

    it 'does ticket show and response format (04.01)' do
      title = "ticket testagent#{SecureRandom.uuid}"
      ticket = create(
        :ticket,
        title:         title,
        group:         ticket_group,
        customer_id:   customer.id,
        updated_by_id: agent.id,
        created_by_id: agent.id,
      )
      authenticated_as(agent)
      get "/api/v1/tickets/#{ticket.id}", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['id']).to eq(ticket.id)
      expect(json_response['title']).to eq(ticket.title)
      expect(json_response['group']).to be_falsey
      expect(json_response['priority']).to be_falsey
      expect(json_response['owner']).to be_falsey
      expect(json_response['customer_id']).to eq(ticket.customer_id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)

      get "/api/v1/tickets/#{ticket.id}?expand=true", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['id']).to eq(ticket.id)
      expect(json_response['title']).to eq(ticket.title)
      expect(json_response['customer_id']).to eq(ticket.customer_id)
      expect(json_response['group']).to eq(ticket.group.name)
      expect(json_response['priority']).to eq(ticket.priority.name)
      expect(json_response['owner']).to eq(ticket.owner.login)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)

      get "/api/v1/tickets/#{ticket.id}?expand=false", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['id']).to eq(ticket.id)
      expect(json_response['title']).to eq(ticket.title)
      expect(json_response['group']).to be_falsey
      expect(json_response['priority']).to be_falsey
      expect(json_response['owner']).to be_falsey
      expect(json_response['customer_id']).to eq(ticket.customer_id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)

      get "/api/v1/tickets/#{ticket.id}?full=true", params: {}, as: :json
      expect(response).to have_http_status(:ok)

      expect(json_response).to be_a(Hash)
      expect(json_response['id']).to eq(ticket.id)
      expect(json_response['assets']).to be_truthy
      expect(json_response['assets']['Ticket']).to be_truthy
      expect(json_response['assets']['Ticket'][ticket.id.to_s]).to be_truthy
      expect(json_response['assets']['Ticket'][ticket.id.to_s]['id']).to eq(ticket.id)
      expect(json_response['assets']['Ticket'][ticket.id.to_s]['title']).to eq(ticket.title)
      expect(json_response['assets']['Ticket'][ticket.id.to_s]['customer_id']).to eq(ticket.customer_id)

      expect(json_response['assets']['User']).to be_truthy
      expect(json_response['assets']['User'][agent.id.to_s]).to be_truthy
      expect(json_response['assets']['User'][agent.id.to_s]['id']).to eq(agent.id)
      expect(json_response['assets']['User'][agent.id.to_s]['firstname']).to eq(agent.firstname)
      expect(json_response['assets']['User'][agent.id.to_s]['lastname']).to eq(agent.lastname)

      expect(json_response['assets']['User']).to be_truthy
      expect(json_response['assets']['User'][customer.id.to_s]).to be_truthy
      expect(json_response['assets']['User'][customer.id.to_s]['id']).to eq(customer.id)
      expect(json_response['assets']['User'][customer.id.to_s]['firstname']).to eq(customer.firstname)
      expect(json_response['assets']['User'][customer.id.to_s]['lastname']).to eq(customer.lastname)

      get "/api/v1/tickets/#{ticket.id}?full=false", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['id']).to eq(ticket.id)
      expect(json_response['title']).to eq(ticket.title)
      expect(json_response['group']).to be_falsey
      expect(json_response['priority']).to be_falsey
      expect(json_response['owner']).to be_falsey
      expect(json_response['customer_id']).to eq(ticket.customer_id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)
    end

    it 'does ticket index and response format (04.02)' do
      title = "ticket testagent#{SecureRandom.uuid}"
      ticket = create(
        :ticket,
        title:         title,
        group:         ticket_group,
        customer_id:   customer.id,
        updated_by_id: agent.id,
        created_by_id: agent.id,
      )
      authenticated_as(agent)
      get '/api/v1/tickets', params: {}, as: :json
      expect(response).to have_http_status(:ok)

      expect(json_response).to be_a(Array)
      expect(json_response[0]).to be_a(Hash)
      expect(json_response[0]['id']).to eq(1)
      expect(json_response[1]['id']).to eq(ticket.id)
      expect(json_response[1]['title']).to eq(ticket.title)
      expect(json_response[1]['group']).to be_falsey
      expect(json_response[1]['priority']).to be_falsey
      expect(json_response[1]['owner']).to be_falsey
      expect(json_response[1]['customer_id']).to eq(ticket.customer_id)
      expect(json_response[1]['updated_by_id']).to eq(agent.id)
      expect(json_response[1]['created_by_id']).to eq(agent.id)

      get '/api/v1/tickets?expand=true', params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Array)
      expect(json_response[0]).to be_a(Hash)
      expect(json_response[0]['id']).to eq(1)
      expect(json_response[1]['id']).to eq(ticket.id)
      expect(json_response[1]['title']).to eq(ticket.title)
      expect(json_response[1]['customer_id']).to eq(ticket.customer_id)
      expect(json_response[1]['group']).to eq(ticket.group.name)
      expect(json_response[1]['priority']).to eq(ticket.priority.name)
      expect(json_response[1]['owner']).to eq(ticket.owner.login)
      expect(json_response[1]['updated_by_id']).to eq(agent.id)
      expect(json_response[1]['created_by_id']).to eq(agent.id)

      get '/api/v1/tickets?expand=false', params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Array)
      expect(json_response[0]).to be_a(Hash)
      expect(json_response[0]['id']).to eq(1)
      expect(json_response[1]['id']).to eq(ticket.id)
      expect(json_response[1]['title']).to eq(ticket.title)
      expect(json_response[1]['group']).to be_falsey
      expect(json_response[1]['priority']).to be_falsey
      expect(json_response[1]['owner']).to be_falsey
      expect(json_response[1]['customer_id']).to eq(ticket.customer_id)
      expect(json_response[1]['updated_by_id']).to eq(agent.id)
      expect(json_response[1]['created_by_id']).to eq(agent.id)

      get '/api/v1/tickets?full=true', params: {}, as: :json
      expect(response).to have_http_status(:ok)

      expect(json_response).to be_a(Hash)
      expect(json_response['record_ids'].class).to eq(Array)
      expect(json_response['record_ids'][0]).to eq(1)
      expect(json_response['record_ids'][1]).to eq(ticket.id)
      expect(json_response['assets']).to be_truthy
      expect(json_response['assets']['Ticket']).to be_truthy
      expect(json_response['assets']['Ticket'][ticket.id.to_s]).to be_truthy
      expect(json_response['assets']['Ticket'][ticket.id.to_s]['id']).to eq(ticket.id)
      expect(json_response['assets']['Ticket'][ticket.id.to_s]['title']).to eq(ticket.title)
      expect(json_response['assets']['Ticket'][ticket.id.to_s]['customer_id']).to eq(ticket.customer_id)

      expect(json_response['assets']['User']).to be_truthy
      expect(json_response['assets']['User'][agent.id.to_s]).to be_truthy
      expect(json_response['assets']['User'][agent.id.to_s]['id']).to eq(agent.id)
      expect(json_response['assets']['User'][agent.id.to_s]['firstname']).to eq(agent.firstname)
      expect(json_response['assets']['User'][agent.id.to_s]['lastname']).to eq(agent.lastname)

      expect(json_response['assets']['User']).to be_truthy
      expect(json_response['assets']['User'][customer.id.to_s]).to be_truthy
      expect(json_response['assets']['User'][customer.id.to_s]['id']).to eq(customer.id)
      expect(json_response['assets']['User'][customer.id.to_s]['firstname']).to eq(customer.firstname)
      expect(json_response['assets']['User'][customer.id.to_s]['lastname']).to eq(customer.lastname)

      get '/api/v1/tickets?full=false', params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Array)
      expect(json_response[0]).to be_a(Hash)
      expect(json_response[0]['id']).to eq(1)
      expect(json_response[1]['id']).to eq(ticket.id)
      expect(json_response[1]['title']).to eq(ticket.title)
      expect(json_response[1]['group']).to be_falsey
      expect(json_response[1]['priority']).to be_falsey
      expect(json_response[1]['owner']).to be_falsey
      expect(json_response[1]['customer_id']).to eq(ticket.customer_id)
      expect(json_response[1]['updated_by_id']).to eq(agent.id)
      expect(json_response[1]['created_by_id']).to eq(agent.id)
    end

    it 'does ticket create and response format (04.03)' do
      title = "ticket testagent#{SecureRandom.uuid}"
      params = {
        title:       title,
        group:       ticket_group.name,
        customer_id: customer.id,
        state:       'new',
        priority:    '2 normal',
        article:     {
          body: 'some test 123',
        },
      }
      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)

      ticket = Ticket.find(json_response['id'])
      expect(json_response['state_id']).to eq(ticket.state_id)
      expect(json_response['state']).to be_falsey
      expect(json_response['priority_id']).to eq(ticket.priority_id)
      expect(json_response['priority']).to be_falsey
      expect(json_response['group_id']).to eq(ticket.group_id)
      expect(json_response['group']).to be_falsey
      expect(json_response['title']).to eq(title)
      expect(json_response['customer_id']).to eq(customer.id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)

      post '/api/v1/tickets?expand=true', params: params, as: :json
      expect(response).to have_http_status(:created)
      expect(json_response).to be_a(Hash)

      ticket = Ticket.find(json_response['id'])
      expect(json_response['state_id']).to eq(ticket.state_id)
      expect(json_response['state']).to eq(ticket.state.name)
      expect(json_response['priority_id']).to eq(ticket.priority_id)
      expect(json_response['priority']).to eq(ticket.priority.name)
      expect(json_response['group_id']).to eq(ticket.group_id)
      expect(json_response['group']).to eq(ticket.group.name)
      expect(json_response['title']).to eq(title)
      expect(json_response['customer_id']).to eq(customer.id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)

      post '/api/v1/tickets?full=true', params: params, as: :json
      expect(response).to have_http_status(:created)
      expect(json_response).to be_a(Hash)

      ticket = Ticket.find(json_response['id'])
      expect(json_response['assets']).to be_truthy
      expect(json_response['assets']['Ticket']).to be_truthy
      expect(json_response['assets']['Ticket'][ticket.id.to_s]).to be_truthy
      expect(json_response['assets']['Ticket'][ticket.id.to_s]['id']).to eq(ticket.id)
      expect(json_response['assets']['Ticket'][ticket.id.to_s]['title']).to eq(title)
      expect(json_response['assets']['Ticket'][ticket.id.to_s]['customer_id']).to eq(ticket.customer_id)

      expect(json_response['assets']['User']).to be_truthy
      expect(json_response['assets']['User'][agent.id.to_s]).to be_truthy
      expect(json_response['assets']['User'][agent.id.to_s]['id']).to eq(agent.id)
      expect(json_response['assets']['User'][agent.id.to_s]['firstname']).to eq(agent.firstname)
      expect(json_response['assets']['User'][agent.id.to_s]['lastname']).to eq(agent.lastname)

      expect(json_response['assets']['User']).to be_truthy
      expect(json_response['assets']['User'][customer.id.to_s]).to be_truthy
      expect(json_response['assets']['User'][customer.id.to_s]['id']).to eq(customer.id)
      expect(json_response['assets']['User'][customer.id.to_s]['firstname']).to eq(customer.firstname)
      expect(json_response['assets']['User'][customer.id.to_s]['lastname']).to eq(customer.lastname)

    end

    it 'does ticket update and response formats (04.04)' do
      title = "ticket testagent#{SecureRandom.uuid}"
      ticket = create(
        :ticket,
        title:         title,
        group:         ticket_group,
        customer_id:   customer.id,
        updated_by_id: agent.id,
        created_by_id: agent.id,
      )

      params = {
        title: 'a update ticket #1',
      }
      authenticated_as(agent)
      put "/api/v1/tickets/#{ticket.id}", params: params, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)

      ticket = Ticket.find(json_response['id'])
      expect(json_response['state_id']).to eq(ticket.state_id)
      expect(json_response['state']).to be_falsey
      expect(json_response['priority_id']).to eq(ticket.priority_id)
      expect(json_response['priority']).to be_falsey
      expect(json_response['group_id']).to eq(ticket.group_id)
      expect(json_response['group']).to be_falsey
      expect(json_response['title']).to eq('a update ticket #1')
      expect(json_response['customer_id']).to eq(customer.id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)

      params = {
        title: 'a update ticket #2',
      }
      put "/api/v1/tickets/#{ticket.id}?expand=true", params: params, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)

      ticket = Ticket.find(json_response['id'])
      expect(json_response['state_id']).to eq(ticket.state_id)
      expect(json_response['state']).to eq(ticket.state.name)
      expect(json_response['priority_id']).to eq(ticket.priority_id)
      expect(json_response['priority']).to eq(ticket.priority.name)
      expect(json_response['group_id']).to eq(ticket.group_id)
      expect(json_response['group']).to eq(ticket.group.name)
      expect(json_response['title']).to eq('a update ticket #2')
      expect(json_response['customer_id']).to eq(customer.id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)

      params = {
        title: 'a update ticket #3',
      }
      put "/api/v1/tickets/#{ticket.id}?full=true", params: params, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)

      ticket = Ticket.find(json_response['id'])
      expect(json_response['assets']).to be_truthy
      expect(json_response['assets']['Ticket']).to be_truthy
      expect(json_response['assets']['Ticket'][ticket.id.to_s]).to be_truthy
      expect(json_response['assets']['Ticket'][ticket.id.to_s]['id']).to eq(ticket.id)
      expect(json_response['assets']['Ticket'][ticket.id.to_s]['title']).to eq('a update ticket #3')
      expect(json_response['assets']['Ticket'][ticket.id.to_s]['customer_id']).to eq(ticket.customer_id)

      expect(json_response['assets']['User']).to be_truthy
      expect(json_response['assets']['User'][agent.id.to_s]).to be_truthy
      expect(json_response['assets']['User'][agent.id.to_s]['id']).to eq(agent.id)
      expect(json_response['assets']['User'][agent.id.to_s]['firstname']).to eq(agent.firstname)
      expect(json_response['assets']['User'][agent.id.to_s]['lastname']).to eq(agent.lastname)

      expect(json_response['assets']['User']).to be_truthy
      expect(json_response['assets']['User'][customer.id.to_s]).to be_truthy
      expect(json_response['assets']['User'][customer.id.to_s]['id']).to eq(customer.id)
      expect(json_response['assets']['User'][customer.id.to_s]['firstname']).to eq(customer.firstname)
      expect(json_response['assets']['User'][customer.id.to_s]['lastname']).to eq(customer.lastname)

      # it should be not possible to modify the ticket number
      expected_ticket_number = ticket.number
      params = {
        title:  'a update ticket #4',
        number: '77777',
      }
      put "/api/v1/tickets/#{ticket.id}?full=true", params: params, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)

      ticket = Ticket.find(json_response['id'])
      expect(json_response['assets']['Ticket'][ticket.id.to_s]['title']).to eq('a update ticket #4')
      expect(json_response['assets']['Ticket'][ticket.id.to_s]['number']).to eq(expected_ticket_number)
    end

    it 'does ticket update with empty article param' do
      title = 'a new ticket'
      ticket = create(
        :ticket,
        title:         title,
        group:         ticket_group,
        customer_id:   customer.id,
        updated_by_id: agent.id,
        created_by_id: agent.id,
      )

      params = {
        state:   Ticket::State.lookup(name: 'close'),
        article: {}
      }
      authenticated_as(agent)
      put "/api/v1/tickets/#{ticket.id}", params: params, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)

      expect(json_response['state_id']).to eq(ticket.state_id)
      expect(json_response['state']).to be_falsey
      expect(json_response['priority_id']).to eq(ticket.priority_id)
      expect(json_response['priority']).to be_falsey
      expect(json_response['group_id']).to eq(ticket.group_id)
      expect(json_response['group']).to be_falsey
      expect(json_response['customer_id']).to eq(customer.id)
      expect(json_response['updated_by_id']).to eq(agent.id)
      expect(json_response['created_by_id']).to eq(agent.id)
      expect(json_response['state_id']).to eq(Ticket::State.lookup(name: 'new').id)
      expect(json_response['title']).to eq(ticket.title)
      expect(ticket.articles.count).to eq(0)
    end

    it 'does ticket update with article and sets online notification as seen', performs_jobs: true do
      other_agent = create(:agent, groups: [ticket_group])
      ticket = create(
        :ticket,
        title:         'test ticket',
        group:         ticket_group,
        owner:         other_agent,
        customer_id:   customer.id,
        updated_by_id: other_agent.id,
        created_by_id: other_agent.id,
      )

      # Create an online notification for the ticket owner (not the agent doing the update)
      online_notification = create(:online_notification, o_id: ticket.id, user_id: other_agent.id, seen: false)

      params = {
        state:   'closed',
        article: {
          body:         'test article',
          content_type: 'text/plain',
          type:         'note',
          sender:       'Agent',
        }
      }
      authenticated_as(agent)

      # Perform the update with ticket update and article in a transaction.
      put "/api/v1/tickets/#{ticket.id}", params: params, as: :json

      expect(response).to have_http_status(:ok)

      # Execute the enqueued job
      perform_enqueued_jobs

      # Verify the notification was marked as seen
      expect(online_notification.reload.seen).to be true
    end

    describe 'X-Zammad-Suppress-Notifications header', performs_jobs: true do
      let(:other_agent) do
        create(:agent, :preferencable, groups: [ticket_group], notification_group_ids: [ticket_group.id])
      end
      let(:ticket) do
        create(:ticket, group: ticket_group, owner: other_agent, customer_id: customer.id,
               updated_by_id: other_agent.id, created_by_id: other_agent.id)
      end
      let(:delivered_emails) { [] }

      before do
        allow(NotificationFactory::Mailer).to receive(:deliver) { |data| delivered_emails << data }
        ticket # ensure ticket is created before authenticated_as sets up headers
        TransactionDispatcher.reset
        clear_jobs
      end

      it 'enqueues the transaction job with disable_notification: true when header is set' do
        authenticated_as(agent)

        put "/api/v1/tickets/#{ticket.id}",
            params:  { title: 'Updated title' },
            headers: { 'X-Zammad-Suppress-Notifications' => 'true' },
            as:      :json

        expect(TransactionJob).to have_been_enqueued.with(anything, hash_including(disable_notification: true)).at_least(:once)
      end

      it 'enqueues the transaction job without disable_notification when header is absent', :aggregate_failures do
        authenticated_as(agent)

        put "/api/v1/tickets/#{ticket.id}",
            params: { title: 'Updated title' },
            as:     :json

        expect(TransactionJob).to have_been_enqueued.at_least(:once)
        expect(TransactionJob).not_to have_been_enqueued.with(anything, hash_including(disable_notification: true)).at_least(:once)
      end

      it 'does not notify the ticket owner when header is set', :aggregate_failures do
        authenticated_as(agent)

        put "/api/v1/tickets/#{ticket.id}",
            params:  { title: 'Updated title' },
            headers: { 'X-Zammad-Suppress-Notifications' => 'true' },
            as:      :json

        perform_enqueued_jobs(only: TransactionJob)

        expect(response).to have_http_status(:ok)
        expect(OnlineNotification.where(object_lookup_id: ObjectLookup.by_name('Ticket'), user_id: other_agent.id, o_id: ticket.id)).to be_empty
        expect(delivered_emails).to be_empty
      end

      it 'notifies the ticket owner when header is absent', :aggregate_failures do
        authenticated_as(agent)

        put "/api/v1/tickets/#{ticket.id}",
            params: { title: 'Updated title' },
            as:     :json

        perform_enqueued_jobs(only: TransactionJob)

        expect(response).to have_http_status(:ok)
        expect(OnlineNotification.where(object_lookup_id: ObjectLookup.by_name('Ticket'), user_id: other_agent.id, o_id: ticket.id)).to exist
        expect(delivered_emails).to include(hash_including(recipient: have_attributes(email: other_agent.email)))
      end

      it 'does not notify group agents on ticket create when header is set', :aggregate_failures do
        authenticated_as(agent)

        post '/api/v1/tickets',
             params:  {
               title:       'Created with suppressed notifications',
               group:       ticket_group.name,
               customer_id: customer.id,
               article:     { body: 'some body', type: 'note' },
             },
             headers: { 'X-Zammad-Suppress-Notifications' => 'true' },
             as:      :json

        perform_enqueued_jobs(only: TransactionJob)

        expect(response).to have_http_status(:created)
        expect(OnlineNotification.where(object_lookup_id: ObjectLookup.by_name('Ticket'), user_id: other_agent.id, o_id: json_response['id'])).to be_empty
        expect(delivered_emails).to be_empty
      end

      it 'notifies group agents on ticket create when header is absent', :aggregate_failures do
        authenticated_as(agent)

        post '/api/v1/tickets',
             params: {
               title:       'Created without suppressed notifications',
               group:       ticket_group.name,
               customer_id: customer.id,
               article:     { body: 'some body', type: 'note' },
             },
             as:     :json

        perform_enqueued_jobs(only: TransactionJob)

        expect(response).to have_http_status(:created)
        expect(OnlineNotification.where(object_lookup_id: ObjectLookup.by_name('Ticket'), user_id: other_agent.id, o_id: json_response['id'])).to exist
        expect(delivered_emails).to include(hash_including(recipient: have_attributes(email: other_agent.email)))
      end

      it 'suppresses notifications on article create when header is set' do
        authenticated_as(agent)

        post '/api/v1/ticket_articles',
             params:  { ticket_id: ticket.id, body: 'note', type: 'note', sender: 'Agent' },
             headers: { 'X-Zammad-Suppress-Notifications' => 'true' },
             as:      :json

        expect(TransactionJob).to have_been_enqueued.with(anything, hash_including(disable_notification: true)).at_least(:once)
      end

      it 'suppresses notifications on ticket create when header is set' do
        authenticated_as(agent)

        post '/api/v1/tickets',
             params:  { title: 'New ticket', group: ticket_group.name, customer_id: customer.id, article: { body: 'some body' } },
             headers: { 'X-Zammad-Suppress-Notifications' => 'true' },
             as:      :json

        expect(TransactionJob).to have_been_enqueued.with(anything, hash_including(disable_notification: true)).at_least(:once)
      end

      it 'ignores the header for customers — only agents can suppress notifications', :aggregate_failures do
        authenticated_as(customer)

        post '/api/v1/ticket_articles',
             params:  { ticket_id: ticket.id, body: 'note', type: 'note', sender: 'Customer' },
             headers: { 'X-Zammad-Suppress-Notifications' => 'true' },
             as:      :json

        expect(TransactionJob).to have_been_enqueued.at_least(:once)
        expect(TransactionJob).not_to have_been_enqueued.with(anything, hash_including(disable_notification: true)).at_least(:once)
      end
    end

    describe 'trigger results in update response' do
      let(:ticket)        { create(:ticket, group: ticket_group, customer_id: customer.id) }
      let(:high_priority) { Ticket::Priority.find_by(name: '3 high') }
      let(:trigger) do
        create(:trigger,
               :conditionable,
               condition_ticket_action:  :update,
               execution_condition_mode: 'always',
               perform:                  { 'ticket.priority_id' => { 'value' => high_priority.id.to_s } })
      end

      before do
        ticket
        trigger
        # Drop buffered events from factory creation, so the request's update
        # event is not merged into a leftover create event.
        TransactionDispatcher.reset
        authenticated_as(agent)
      end

      # Sync triggers are dispatched inside the endpoint's Transaction.execute,
      # before the response is rendered - their changes must be part of it.
      it 'returns attributes changed by triggers' do
        put "/api/v1/tickets/#{ticket.id}", params: { title: 'trigger me' }, as: :json

        expect(json_response['priority_id']).to eq(high_priority.id)
      end

      it 'returns attributes changed by triggers on title update' do
        put "/api/v1/tickets/#{ticket.id}/update_title", params: { title: 'trigger me' }, as: :json

        expect(json_response['priority_id']).to eq(high_priority.id)
      end

      it 'returns attributes changed by triggers on customer update' do
        other_customer = create(:customer)

        put "/api/v1/tickets/#{ticket.id}/update_customer", params: { customer_id: other_customer.id }, as: :json

        expect(json_response['priority_id']).to eq(high_priority.id)
      end
    end

    describe 'asset redaction in ticket write responses' do
      let(:organization) do
        create(:organization, note: 'internal organization note', domain: 'internal.example.com', vip: true)
      end
      let(:owner) do
        create(:agent,
               groups:     Group.all,
               phone:      '+49 30 111111',
               mobile:     '+49 170 222222',
               department: 'Internal Department',
               street:     'Internal Street 1',
               zip:        '12345',
               city:       'Internalcity',
               country:    'Germany',
               note:       'internal agent note')
      end
      let(:ticket_customer) do
        create(:customer, organization: organization, phone: '+49 30 999999', note: 'internal customer note')
      end
      let(:ticket) do
        create(:ticket, group: ticket_group, customer: ticket_customer, owner: owner)
      end

      before do
        ticket
        # Drop buffered events from factory creation, so the dispatch during the
        # request only handles the events the request itself produced.
        TransactionDispatcher.reset
        authenticated_as(ticket_customer)
      end

      def asset_attributes(body, model, id)
        body.dig('assets', model, id.to_s)
      end

      def asset_attribute_names(body)
        body['assets'].transform_values do |records|
          records.transform_values { |attributes| attributes.keys.sort }
        end
      end

      # The asset filters redact sensitive attributes based on UserInfo. Transaction dispatch runs
      # inside the endpoint's Transaction.execute, i.e. before the response is rendered - it must
      # not strip the user context those filters depend on.
      shared_examples 'redacting assets like the matching read response' do |parameter|
        let(:update_params) { { title: 'updated by customer' } }

        it 'redacts sensitive attributes of the ticket owner', :aggregate_failures do
          put "/api/v1/tickets/#{ticket.id}?#{parameter}", params: update_params, as: :json

          expect(response).to have_http_status(:ok)
          expect(asset_attributes(json_response, 'User', owner.id).keys)
            .not_to include('phone', 'mobile', 'department', 'street', 'zip', 'city', 'country', 'note', 'email')
        end

        it 'redacts internal attributes of the organization', :aggregate_failures do
          put "/api/v1/tickets/#{ticket.id}?#{parameter}", params: update_params, as: :json

          expect(response).to have_http_status(:ok)
          expect(asset_attributes(json_response, 'Organization', organization.id).keys)
            .not_to include('note', 'domain', 'vip')
        end

        it 'redacts sensitive attributes of the requesting customer', :aggregate_failures do
          put "/api/v1/tickets/#{ticket.id}?#{parameter}", params: update_params, as: :json

          expect(response).to have_http_status(:ok)
          expect(asset_attributes(json_response, 'User', ticket_customer.id).keys)
            .not_to include('phone', 'note')
        end

        it 'renders the same asset attributes as the read response', :aggregate_failures do
          put "/api/v1/tickets/#{ticket.id}?#{parameter}", params: update_params, as: :json
          update_response = json_response

          get "/api/v1/tickets/#{ticket.id}?#{parameter}", params: {}, as: :json

          expect(response).to have_http_status(:ok)
          expect(asset_attribute_names(update_response)).to eq(asset_attribute_names(json_response))
        end

        # Service::Base#execute restores the current user id on its own, so this endpoint relies
        # on two independent safeguards.
        it 'redacts sensitive attributes on title update', :aggregate_failures do
          put "/api/v1/tickets/#{ticket.id}/update_title?#{parameter}", params: update_params, as: :json

          expect(response).to have_http_status(:ok)
          expect(asset_attributes(json_response, 'User', owner.id).keys)
            .not_to include('phone', 'mobile', 'note', 'email')
        end

        it 'redacts sensitive attributes on ticket creation', :aggregate_failures do
          params = {
            title:    'created by customer',
            group_id: ticket_group.id,
            article:  { body: 'some body' },
          }

          post "/api/v1/tickets?#{parameter}", params: params, as: :json

          expect(response).to have_http_status(:created)
          expect(asset_attributes(json_response, 'Organization', organization.id).keys)
            .not_to include('note', 'domain', 'vip')
          expect(asset_attributes(json_response, 'User', ticket_customer.id).keys)
            .not_to include('phone', 'note')
        end
      end

      it_behaves_like 'redacting assets like the matching read response', 'full=true'
      it_behaves_like 'redacting assets like the matching read response', 'all=true'
    end

    it 'does ticket split with html - check attachments (05.01)' do
      ticket = create(
        :ticket,
        title:         'some title',
        group:         ticket_group,
        customer_id:   customer.id,
        updated_by_id: agent.id,
        created_by_id: agent.id,
      )
      article = create(
        :ticket_article,
        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',
        ticket_id:    ticket.id,
      )
      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',
             })

      authenticated_as(customer)
      get "/api/v1/ticket_split?ticket_id=#{ticket.id}&article_id=#{article.id}&form_id=a464a40c-e84e-42d7-ab6e-5daea2bc1502", params: {}, as: :json
      expect(response).to have_http_status(:forbidden)

      authenticated_as(agent)
      get "/api/v1/ticket_split?ticket_id=#{ticket.id}&article_id=#{article.id}&form_id=a464a40c-e84e-42d7-ab6e-5daea2bc1502", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['assets']).to be_truthy
      expect(json_response['assets']['Ticket']).to be_truthy
      expect(json_response['assets']['Ticket'][ticket.id.to_s]).to be_truthy
      expect(json_response['assets']['TicketArticle'][article.id.to_s]).to be_truthy
      expect(json_response['attachments']).to be_truthy
      expect(json_response['attachments'].count).to eq(3)

      get "/api/v1/ticket_split?ticket_id=#{ticket.id}&article_id=#{article.id}&form_id=a464a40c-e84e-42d7-ab6e-5daea2bc1502", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['assets']).to be_truthy
      expect(json_response['assets']['Ticket']).to be_truthy
      expect(json_response['assets']['Ticket'][ticket.id.to_s]).to be_truthy
      expect(json_response['assets']['TicketArticle'][article.id.to_s]).to be_truthy
      expect(json_response['attachments']).to be_truthy
      expect(json_response['attachments'].count).to eq(0)

    end

    it 'does ticket split with plain - check attachments (05.02)' do
      ticket = create(
        :ticket,
        title:         'some title',
        group:         ticket_group,
        customer_id:   customer.id,
        updated_by_id: agent.id,
        created_by_id: agent.id,
      )
      article = create(
        :ticket_article,
        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',
        ticket_id:    ticket.id,
      )
      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',
             })

      authenticated_as(agent)
      get "/api/v1/ticket_split?ticket_id=#{ticket.id}&article_id=#{article.id}&form_id=a464a40c-e84e-42d7-ab6e-5daea2bc1502", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['assets']).to be_truthy
      expect(json_response['assets']['Ticket']).to be_truthy
      expect(json_response['assets']['Ticket'][ticket.id.to_s]).to be_truthy
      expect(json_response['assets']['TicketArticle'][article.id.to_s]).to be_truthy
      expect(json_response['attachments']).to be_truthy
      expect(json_response['attachments'].count).to eq(3)

      get "/api/v1/ticket_split?ticket_id=#{ticket.id}&article_id=#{article.id}&form_id=a464a40c-e84e-42d7-ab6e-5daea2bc1502", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['assets']).to be_truthy
      expect(json_response['assets']['Ticket']).to be_truthy
      expect(json_response['assets']['Ticket'][ticket.id.to_s]).to be_truthy
      expect(json_response['assets']['TicketArticle'][article.id.to_s]).to be_truthy
      expect(json_response['attachments']).to be_truthy
      expect(json_response['attachments'].count).to eq(0)

    end

    it 'does ticket merge (07.01)' do
      group_no_permission = create(:group)
      ticket1 = create(
        :ticket,
        title:       'ticket merge1',
        group:       ticket_group,
        customer_id: customer.id,
      )
      ticket2 = create(
        :ticket,
        title:       'ticket merge2',
        group:       ticket_group,
        customer_id: customer.id,
      )
      ticket3 = create(
        :ticket,
        title:       'ticket merge2',
        group:       group_no_permission,
        customer_id: customer.id,
      )

      authenticated_as(customer)
      put "/api/v1/ticket_merge/#{ticket2.id}/#{ticket1.id}", params: {}, as: :json
      expect(response).to have_http_status(:forbidden)

      authenticated_as(agent)
      put "/api/v1/ticket_merge/#{ticket2.id}/#{ticket1.id}", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['result']).to eq('failed')
      expect(json_response['message']).to eq('The target ticket number could not be found.')

      put "/api/v1/ticket_merge/#{ticket3.id}/#{ticket1.number}", 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')
      expect(json_response['error_human']).to eq('Not authorized')

      put "/api/v1/ticket_merge/#{ticket1.id}/#{ticket3.number}", 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')
      expect(json_response['error_human']).to eq('Not authorized')

      put "/api/v1/ticket_merge/#{ticket1.id}/#{ticket2.number}", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['result']).to eq('success')
      expect(json_response['target_ticket']['id']).to eq(ticket2.id)
    end

    it 'does ticket merge - change permission (07.02)' do
      group_change_permission = Group.create!(
        name:          'GroupWithChangePermission',
        active:        true,
        updated_by_id: 1,
        created_by_id: 1,
      )
      ticket1 = create(
        :ticket,
        title:       'ticket merge1',
        group:       group_change_permission,
        customer_id: customer.id,
      )
      ticket2 = create(
        :ticket,
        title:       'ticket merge2',
        group:       group_change_permission,
        customer_id: customer.id,
      )

      agent.group_names_access_map = { group_change_permission.name => %w[read change] }

      authenticated_as(agent)
      put "/api/v1/ticket_merge/#{ticket1.id}/#{ticket2.number}", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['result']).to eq('success')
      expect(json_response['target_ticket']['id']).to eq(ticket2.id)
    end

    it 'does ticket search sorted (08.01)' do
      title = "ticket pagination #{SecureRandom.uuid}"

      ticket1 = create(
        :ticket,
        title:       "#{title} A",
        group:       ticket_group,
        customer_id: customer.id,
        created_at:  '2018-02-05 17:42:00',
        updated_at:  '2018-02-05 20:42:00',
      )
      create(
        :ticket_article,
        type:      Ticket::Article::Type.lookup(name: 'note'),
        sender:    Ticket::Article::Sender.lookup(name: 'Customer'),
        ticket_id: ticket1.id,
      )

      ticket2 = create(
        :ticket,
        title:       "#{title} B",
        group:       ticket_group,
        customer_id: customer.id,
        state:       Ticket::State.lookup(name: 'new'),
        priority:    Ticket::Priority.lookup(name: '3 hoch'),
        created_at:  '2018-02-05 19:42:00',
        updated_at:  '2018-02-05 19:42:00',
      )
      create(
        :ticket_article,
        type:      Ticket::Article::Type.lookup(name: 'note'),
        sender:    Ticket::Article::Sender.lookup(name: 'Customer'),
        ticket_id: ticket2.id,
      )

      authenticated_as(admin)
      get "/api/v1/tickets/search?query=#{CGI.escape(title)}&limit=40&full=true", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['record_ids']).to eq([ticket2.id, ticket1.id])

      authenticated_as(admin)
      get "/api/v1/tickets/search?query=#{CGI.escape(title)}&limit=40&full=true", params: { sort_by: 'created_at', order_by: 'asc' }, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['record_ids']).to eq([ticket1.id, ticket2.id])

      authenticated_as(admin)
      get "/api/v1/tickets/search?query=#{CGI.escape(title)}&limit=40&full=true", params: { sort_by: 'title', order_by: 'asc' }, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['record_ids']).to eq([ticket1.id, ticket2.id])

      authenticated_as(admin)
      get "/api/v1/tickets/search?query=#{CGI.escape(title)}&limit=40&full=true", params: { sort_by: 'title', order_by: 'desc' }, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['record_ids']).to eq([ticket2.id, ticket1.id])

      authenticated_as(admin)
      get "/api/v1/tickets/search?query=#{CGI.escape(title)}&limit=40&full=true", params: { sort_by: %w[created_at updated_at], order_by: %w[asc asc] }, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['record_ids']).to eq([ticket1.id, ticket2.id])

      authenticated_as(admin)
      get "/api/v1/tickets/search?query=#{CGI.escape(title)}&limit=40&full=true", params: { sort_by: %w[created_at updated_at], order_by: %w[desc asc] }, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['record_ids']).to eq([ticket2.id, ticket1.id])
    end

    it 'does ticket history' do
      ticket1 = create(
        :ticket,
        title:       'some title',
        group:       ticket_group,
        customer_id: customer.id,
      )
      create(
        :ticket_article,
        type:      Ticket::Article::Type.lookup(name: 'note'),
        sender:    Ticket::Article::Sender.lookup(name: 'Customer'),
        ticket_id: ticket1.id,
      )

      authenticated_as(agent)
      get "/api/v1/ticket_history/#{ticket1.id}", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['history'].class).to eq(Array)
      expect(json_response['assets'].class).to eq(Hash)
      expect(json_response['assets']['User'][customer.id.to_s]).not_to be_nil
      expect(json_response['assets']['Ticket'][ticket1.id.to_s]).not_to be_nil

      authenticated_as(customer)
      get "/api/v1/ticket_history/#{ticket1.id}", params: {}, as: :json
      expect(response).to have_http_status(:forbidden)
    end

    it 'does ticket related' do
      ticket1 = create(
        :ticket,
        title:       'some title',
        group:       ticket_group,
        customer_id: customer.id,
      )

      authenticated_as(agent)
      get "/api/v1/ticket_related/#{ticket1.id}", params: {}, as: :json
      expect(response).to have_http_status(:ok)

      authenticated_as(create(:agent, groups: []))
      get "/api/v1/ticket_related/#{ticket1.id}", params: {}, as: :json
      expect(response).to have_http_status(:forbidden)

      authenticated_as(customer)
      get "/api/v1/ticket_related/#{ticket1.id}", params: {}, as: :json
      expect(response).to have_http_status(:forbidden)
    end

    it 'does ticket recent' do
      authenticated_as(agent)
      get '/api/v1/ticket_recent', params: {}, as: :json
      expect(response).to have_http_status(:ok)

      authenticated_as(customer)
      get '/api/v1/ticket_recent', params: {}, as: :json
      expect(response).to have_http_status(:forbidden)
    end

  end

  describe 'mentions' do
    let(:user1) { create(:agent, groups: [ticket_group]) }
    let(:user2) { create(:agent, groups: [ticket_group]) }
    let(:user3) { create(:agent, groups: [ticket_group]) }

    def new_ticket_with_mentions(*user_ids)
      params = {
        title:    'a new ticket #11',
        group:    ticket_group.name,
        customer: {
          firstname: 'some firstname',
          lastname:  'some lastname',
          email:     'some_new_customer@example.com',
        },
        article:  {
          body: 'some test 123',
        },
        mentions: user_ids
      }
      authenticated_as(agent)
      post '/api/v1/tickets', params: params, as: :json

      json_response
    end

    it 'create ticket with mentions' do
      new_ticket_with_mentions(user1.id, user2.id, user3.id)
      expect(response).to have_http_status(:created)
      expect(Mention.count).to eq(3)
    end

    it 'create ticket with one of mentions being invalid' do
      new_ticket_with_mentions(user1.id, user2.id, create(:customer).id)
      expect(response).to have_http_status(:unprocessable_content)
      expect(Mention.count).to eq(0)
    end

    it 'check ticket get' do
      ticket = new_ticket_with_mentions(user1.id, user2.id, user3.id)

      get "/api/v1/tickets/#{ticket['id']}?all=true", params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response['mentions'].count).to eq(3)
      expect(json_response['assets']['Mention'].count).to eq(3)
    end
  end

  describe 'stats' do
    let(:ticket1) { create(:ticket, customer: customer, organization: organization, group: ticket_group) }
    let(:ticket2)      { create(:ticket, customer: customer, organization: organization, group: ticket_group) }
    let(:ticket3)      { create(:ticket, customer: customer, organization: organization, group: ticket_group) }
    let(:customer)     { create(:customer, organization: organization) }
    let(:organization) { create(:organization, shared: false) }

    before do
      authenticated_as(admin)

      ticket1
      travel 2.minutes
      ticket2
      travel 2.minutes
      ticket3
      travel 2.minutes
      ticket2.touch
    end

    # https://github.com/zammad/zammad/issues/2296
    it 'orders tickets by created_at desc (#2296)' do
      get '/api/v1/ticket_stats', params: { organization_id: organization.id, user_id: customer.id }, as: :json

      expect(response).to have_http_status(:ok)
      expect(json_response)
        .to be_a(Hash)
        .and include('user' => hash_including('open_ids' => [ticket3.id, ticket2.id, ticket1.id]))
        .and include('organization' => hash_including('open_ids' => [ticket3.id, ticket2.id, ticket1.id]))
    end

  end

  describe '/api/v1/tickets' do
    subject(:ticket) { create(:ticket, state_name: 'closed') }

    let(:agent)    { create(:agent, groups: [ticket.group]) }
    let(:customer) { ticket.customer }

    describe 'reopening a ticket' do
      shared_examples 'successfully reopen a ticket' do
        it 'succeeds' do
          put "/api/v1/tickets/#{ticket.id}",
              params: { state_id: Ticket::State.find_by(name: 'open').id },
              as:     :json

          expect(response).to have_http_status(:ok)
          expect(json_response).to include('state_id' => Ticket::State.find_by(name: 'open').id)
        end
      end

      shared_examples 'fail to reopen a ticket' do
        it 'fails' do
          put "/api/v1/tickets/#{ticket.id}",
              params: { state_id: Ticket::State.find_by(name: 'open').id },
              as:     :json

          expect(response).to have_http_status(:unprocessable_content)
          expect(json_response).to include('error' => 'Cannot follow-up on a closed ticket. Please create a new ticket.')
        end
      end

      context 'when ticket.group.follow_up_possible = "new_ticket"' do
        before { ticket.group.update(follow_up_possible: 'new_ticket') }

        context 'as agent', authenticated_as: -> { agent } do
          include_examples 'successfully reopen a ticket'
        end

        context 'as customer', authenticated_as: -> { customer } do
          include_examples 'fail to reopen a ticket'
        end
      end
    end
  end

  describe 'POST /api/v1/tickets' do
    let(:group) { create(:group) }
    let(:agent) { create(:agent, groups: [group]) }

    let(:base_params) do
      {
        title:       'a new ticket',
        group:       group.name,
        article:     { content_type: 'text/plain', body: 'some body' },
        customer_id: customer.id,
      }
    end

    describe 'link authorization', authenticated_as: -> { agent } do
      context 'when the target is a Ticket' do
        context 'when the user does not have agent access' do
          let(:target_ticket) { create(:ticket) } # in a group the agent has no access to

          it 'returns forbidden', :aggregate_failures do
            post '/api/v1/tickets',
                 params: base_params.merge(links: { Ticket: { normal: [target_ticket.id] } }),
                 as:     :json

            expect(response).to have_http_status(:forbidden)
            expect(Ticket.find_by(title: base_params[:title])).to be_nil
          end
        end

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

          it 'creates the ticket with the link' do
            post '/api/v1/tickets',
                 params: base_params.merge(links: { Ticket: { normal: [target_ticket.id] } }),
                 as:     :json

            expect(response).to have_http_status(:created)
            expect(Link.list(link_object: 'Ticket', link_object_value: json_response['id']))
              .to include(include('link_object' => 'Ticket', 'link_object_value' => target_ticket.id))
          end
        end
      end

      context 'when the target is a KnowledgeBase::Answer::Translation' do
        include_context 'basic Knowledge Base'

        let(:translation) { internal_answer.translations.first }

        context 'when the user has no access to the KB answer' do
          let(:role)  { create(:role, permission_names: %w[ticket.agent]) }
          let(:agent) { create(:user, groups: [group], roles: [role]) }

          it 'returns forbidden', :aggregate_failures do
            post '/api/v1/tickets',
                 params: base_params.merge(links: { 'KnowledgeBase::Answer::Translation' => { normal: [translation.id] } }),
                 as:     :json

            expect(response).to have_http_status(:forbidden)
            expect(Ticket.find_by(title: base_params[:title])).to be_nil
          end
        end

        context 'when the user reader access to the KB answer' do
          let(:agent) { create(:agent, groups: [group]) }

          it 'creates the ticket with the link' do
            post '/api/v1/tickets',
                 params: base_params.merge(links: { 'KnowledgeBase::Answer::Translation' => { normal: [translation.id] } }),
                 as:     :json

            expect(response).to have_http_status(:created)
            expect(Link.list(link_object: 'Ticket', link_object_value: json_response['id']))
              .to include(include('link_object' => 'KnowledgeBase::Answer::Translation', 'link_object_value' => translation.id))
          end
        end

        context 'when the user editor access to the KB answer' do
          let(:kb_editor_role) { create(:role, permission_names: %w[knowledge_base.editor ticket.agent]) }
          let(:agent)          { create(:agent, groups: [group], roles: [kb_editor_role]) }

          it 'creates the ticket with the link' do
            post '/api/v1/tickets',
                 params: base_params.merge(links: { 'KnowledgeBase::Answer::Translation' => { normal: [translation.id] } }),
                 as:     :json

            expect(response).to have_http_status(:created)
            expect(Link.list(link_object: 'Ticket', link_object_value: json_response['id']))
              .to include(include('link_object' => 'KnowledgeBase::Answer::Translation', 'link_object_value' => translation.id))
          end
        end
      end
    end
  end

  describe 'GET /api/v1/tickets/:id' do

    subject!(:ticket) { create(:ticket) }

    let(:agent) { create(:agent, groups: [ticket.group]) }

    context 'links present', authenticated_as: -> { agent } do

      before do
        create(:link, from: ticket, to: linked)
        get "/api/v1/tickets/#{ticket.id}", params: { all: 'true' }, as: :json
      end

      let(:linked) { create(:ticket, group: ticket.group) }

      it 'is present in response' do
        expect(response).to have_http_status(:ok)
        expect(json_response['links']).to eq([
                                               {
                                                 'link_type'         => 'normal',
                                                 'link_object'       => 'Ticket',
                                                 'link_object_value' => linked.id
                                               }
                                             ])
      end

      context 'no permission to linked Ticket Group' do
        let(:linked) { create(:ticket) }

        it 'is not present in response' do
          expect(response).to have_http_status(:ok)
          expect(json_response['links']).to be_blank
        end
      end
    end

    context 'referencing checklist present', authenticated_as: -> { agent }, current_user_id: 1 do
      let(:referencing_ticket)    { create(:ticket, group: ticket.group) }
      let(:referencing_checklist) { create(:checklist, ticket: referencing_ticket) }

      before do
        Setting.set('checklist', true)
        referencing_checklist.items.create!(ticket:)
        get "/api/v1/tickets/#{ticket.id}", params: { all: 'true' }, as: :json
      end

      it 'is present in response', :aggregate_failures do
        expect(response).to have_http_status(:ok)
        expect(json_response['assets']).to include_assets_of([referencing_checklist, referencing_ticket, *referencing_checklist.items])
      end

      context 'no permission to referencing Ticket Group' do
        let(:referencing_ticket) { create(:ticket) }

        it 'is marked as inaccessible without ticket and item assets', :aggregate_failures do
          expect(response).to have_http_status(:ok)
          expect(json_response.dig('assets', 'Checklist', referencing_checklist.id.to_s)).to eq('id' => referencing_checklist.id, 'ticket_inaccessible' => true)
          expect(json_response['assets']).not_to include_assets_of([referencing_ticket, referencing_ticket.customer, *referencing_checklist.items])
        end
      end
    end
  end

  describe 'GET /api/v1/ticket_customer' do

    subject(:ticket) { create(:ticket, customer: customer_authorized) }

    let(:organization_authorized) { create(:organization) }
    let(:customer_authorized)     { create(:customer, organization: organization_authorized) }

    let(:organization_unauthorized) { create(:organization) }
    let(:customer_unauthorized) { create(:customer, organization: organization_unauthorized) }

    let(:agent) { create(:agent, groups: [ticket.group]) }

    describe 'listing information' do

      before do
        ticket
      end

      shared_examples 'has access' do
        it 'succeeds' do
          get '/api/v1/ticket_customer',
              params: { customer_id: customer_authorized.id },
              as:     :json

          expect(json_response['ticket_ids_open']).to include(ticket.id)
          expect(json_response['ticket_ids_closed']).to be_blank
        end
      end

      shared_examples 'has no access' do
        it 'fails' do
          get '/api/v1/ticket_customer',
              params: { customer_id: customer_authorized.id },
              as:     :json

          expect(json_response['ticket_ids_open']).to be_blank
          expect(json_response['ticket_ids_closed']).to be_blank
          expect(json_response['assets']).to be_blank
        end
      end

      context 'as agent', authenticated_as: -> { agent } do
        include_examples 'has access'
      end

      context 'as authorized customer', authenticated_as: -> { customer_authorized } do
        include_examples 'has no access'
      end

      context 'as unauthorized customer', authenticated_as: -> { customer_unauthorized } do
        include_examples 'has no access'
      end
    end
  end

  describe 'Assign user to multiple organizations #1573' do
    let(:organizations) { create_list(:organization, 3) }
    let(:customer)      { create(:customer, organization: organizations[0], organizations: organizations[1..]) }
    let(:ticket1)       { create(:ticket, customer: customer, organization: organizations[0], group: Group.first) }
    let(:ticket2)       { create(:ticket, customer: customer, organization: organizations[1], group: Group.first) }

    before do
      ticket1 && ticket2
    end

    it 'does return multi organization tickets' do
      authenticated_as(agent)
      post '/api/v1/ticket_stats', params: { organization_id: customer.all_organization_ids, user_id: customer.id }, as: :json

      expect(response).to have_http_status(:ok)
      expect(json_response)
        .to be_a(Hash)
        .and include('user' => hash_including('open_ids' => [ticket2.id, ticket1.id]))
        .and include('organization' => hash_including('open_ids' => [ticket2.id, ticket1.id]))
    end
  end

  describe 'Articles are not indexed properly #4596', performs_jobs: true, searchindex: true do
    let(:ticket) { create(:ticket, group: Group.first) }

    def new_article_body
      params = {
        article: {
          body:         SecureRandom.uuid,
          content_type: 'text/plain',
          internal:     false,
        },
      }
      authenticated_as(agent)
      put "/api/v1/tickets/#{ticket.id}", params: params, as: :json
      expect(response).to have_http_status(:ok)

      perform_enqueued_jobs
      SearchIndexBackend.refresh

      params[:article][:body]
    end

    def delete_article_body
      article = ticket.articles.last
      delete "/api/v1/ticket_articles/#{article.id}"
      expect(response).to have_http_status(:ok)

      perform_enqueued_jobs
      SearchIndexBackend.refresh

      article.body
    end

    before do
      ticket
      searchindex_model_reload([Ticket])
    end

    it 'does find articles after creations', :aggregate_failures do
      expect(SearchIndexBackend.search(new_article_body, 'Ticket', limit: 1)).to be_present
      expect(SearchIndexBackend.search(new_article_body, 'Ticket', limit: 1)).to be_present
      expect(SearchIndexBackend.search(delete_article_body, 'Ticket', limit: 1)).to be_blank
    end
  end

  describe 'Agent with being "ticket.agent" and "ticket.customer" is creating + updating a ticket', :aggregate_failures, authenticated_as: :user do
    let(:group_only_create) { create(:group) }
    let(:user)              { create(:agent_and_customer) }

    before do
      user.group_names_access_map = {
        group_only_create.name => %w[create],
      }
    end

    it 'contains correct information for sender if agent sets himself as customer and responds' do
      pending 'Article metadata does not treat agents acting as their own customer as customer yet.'

      params = {
        title:       'Test title for issue #4647',
        group_id:    group_only_create.id,
        customer_id: user.id,
        article:     {
          type:     'web',
          internal: false,
          sender:   'Customer',
          subject:  'Test subject',
          body:     SecureRandom.uuid,
        },
      }

      post '/api/v1/tickets', params: params, as: :json

      expect(response).to have_http_status(:created)

      ticket = Ticket.last

      expect(ticket.customer_id).to eq(user.id)
      expect(ticket.articles.reload.first).to have_attributes(
        sender: Ticket::Article::Sender.lookup(name: 'Customer'),
        from:   "#{user.fullname} <#{user.email}>",
      )

      response_params = {
        article: {
          body: SecureRandom.uuid,
        },
      }
      put "/api/v1/tickets/#{ticket.id}", params: response_params, as: :json

      expect(response).to have_http_status(:ok)

      expect(ticket.reload.articles.last.sender.name).to eq('Customer')
    end
  end

  describe 'Article contains wrong "origin_by" + "from" information', :aggregate_failures, authenticated_as: :user do
    let(:api_role) do
      role = create(:role, name: 'API', permission_names: ['ticket.agent'])
      role.group_names_access_map = {
        Group.first.name => %w[create change],
      }
      role
    end

    let(:user) { create(:user, roles: [api_role]) }

    it 'contains correct "origin_by" + "from" information' do
      params = {
        title:       'Test title for issue #4647',
        group_id:    Group.first.id,
        customer_id: 'guess:dummy@example.com',
        article:     {
          type:     'web',
          internal: false,
          sender:   'Customer',
          subject:  'Test subject',
          body:     SecureRandom.uuid,
        },
      }

      post '/api/v1/tickets', params: params, as: :json

      expect(response).to have_http_status(:created)

      expect(Ticket.last.articles.first).to have_attributes(
        origin_by_id: User.find_by(email: 'dummy@example.com').id,
        from:         'dummy@example.com',
      )
    end
  end

  describe 'Agents can create new tags even if prohibited by the settings #3501', authenticated_as: :agent do
    let(:tag) { SecureRandom.hex(4) }

    before do
      Setting.set('tag_new', false)
    end

    it 'does create the ticket without tags' do
      params = {
        title:       'a new ticket #3',
        group:       Group.first.name,
        priority:    '2 normal',
        state:       'new',
        customer_id: customer.id,
        tags:        tag,
      }

      post '/api/v1/tickets', params: params, as: :json
      expect(response).to have_http_status(:created)
      expect(Ticket.last.tag_list).to eq([])
    end
  end

  describe 'ticket search parameter with_total_count only works with full=true #5687', authenticated_as: :agent, searchindex: true do
    let(:tickets) { create_list(:ticket, 3, title: 'total test', group: Group.first) }

    before do
      tickets
      searchindex_model_reload([Ticket])
    end

    it 'does search with -none- and with_total_count=false' do
      get '/api/v1/tickets/search?query=total&full=false&with_total_count=false', params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Array)
      expect(json_response.count).to eq(3)
    end

    it 'does search with -none- and with_total_count=true' do
      get '/api/v1/tickets/search?query=total&full=false&with_total_count=true', params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['total_count']).to eq(3)
      expect(json_response['records'].count).to eq(3)
    end

    it 'does search with full=true and with_total_count=false' do
      get '/api/v1/tickets/search?query=total&full=true', params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['total_count']).to eq(3)
      expect(json_response['record_ids'].count).to eq(3)
    end

    it 'does search with full=true and with_total_count=true' do
      get '/api/v1/tickets/search?query=total&full=true&with_total_count=true', params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['total_count']).to eq(3)
      expect(json_response['record_ids'].count).to eq(3)
    end

    it 'does search with expand=true and with_total_count=false' do
      get '/api/v1/tickets/search?query=total&expand=true&with_total_count=false', params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Array)
      expect(json_response.count).to eq(3)
    end

    it 'does search with expand=true and with_total_count=true' do
      get '/api/v1/tickets/search?query=total&expand=true&with_total_count=true', params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['total_count']).to eq(3)
      expect(json_response['records'].count).to eq(3)
    end

    it 'does search with term=total and with_total_count=false' do
      get '/api/v1/tickets/search?query=total&term=total&with_total_count=false', params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Array)
      expect(json_response.count).to eq(3)
    end

    it 'does search with term=total and with_total_count=true' do
      get '/api/v1/tickets/search?query=total&term=total&with_total_count=true', params: {}, as: :json
      expect(response).to have_http_status(:ok)
      expect(json_response).to be_a(Hash)
      expect(json_response['total_count']).to eq(3)
      expect(json_response['records'].count).to eq(3)
    end
  end

  describe 'Case insensitive in customer mail using the API not always true #5785' do
    let(:agent)    { create(:agent, groups: Group.all) }
    let(:customer) { create(:customer, email: 'NEW_HERE@example.com') }

    it 'does create a customer and a ticket for it', :aggregate_failures do
      customer
      expect(customer.reload.email).to eq('new_here@example.com')

      params = {
        title:    'a new ticket #3',
        group_id: Group.first.id,
        priority: '2 normal',
        state:    'new',
        customer: 'NEW_HERE@example.com'
      }
      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)
    end
  end

  describe 'PUT /api/v1/update_title' do
    let(:ticket) { create(:ticket) }
    let(:agent)  { create(:agent, groups: [ticket.group]) }
    let(:title)  { 'Updated title' }

    context 'with an agent', authenticated_as: :agent do
      it 'updates the title' do
        expect { put "/api/v1/tickets/#{ticket.id}/update_title", params: { title: }, as: :json }
          .to change { ticket.reload.title }
          .to(title)
      end

      it 'uses ForcedUpdate service' do
        allow(Service::Ticket::ForcedUpdate).to receive(:execute).and_call_original

        put "/api/v1/tickets/#{ticket.id}/update_title", params: { title:, owner_id: 123 }, as: :json

        expect(Service::Ticket::ForcedUpdate)
          .to have_received(:execute).with(ticket, { title: 'Updated title' }, current_user: agent)
      end

      context 'when agent has no access to the ticket' do
        let(:agent) { create(:agent) }

        it 'access is forbidden' do
          put "/api/v1/tickets/#{ticket.id}/update_title", params: { title: }
          expect(response).to have_http_status(:forbidden)
        end
      end
    end

    context 'with a customer', authenticated_as: -> { ticket.customer } do
      it 'updates the title' do
        expect { put "/api/v1/tickets/#{ticket.id}/update_title", params: { title: }, as: :json }
          .to change { ticket.reload.title }
          .to(title)
      end
    end
  end

  describe 'PUT /api/v1/update_customer' do
    let(:ticket)             { create(:ticket) }
    let(:agent)              { create(:agent, groups: [ticket.group]) }
    let(:title)              { 'Updated title' }
    let(:customer)           { create(:customer, organization:, organizations: [other_organization]) }
    let(:organization)       { create(:organization) }
    let(:other_organization) { create(:organization) }

    context 'with an agent', authenticated_as: :agent do
      it 'updates the customer' do
        put "/api/v1/tickets/#{ticket.id}/update_customer",
            params: { customer_id: customer.id },
            as:     :json

        expect(ticket.reload).to have_attributes(
          customer:,
          organization:,
        )
      end

      it 'updates the customer and the organzization' do
        put "/api/v1/tickets/#{ticket.id}/update_customer",
            params: { customer_id: customer.id, organization_id: other_organization.id },
            as:     :json

        expect(ticket.reload).to have_attributes(
          customer:,
          organization: other_organization,
        )
      end

      it 'uses ForcedUpdate service with customer and organization' do
        allow(Service::Ticket::ForcedUpdate).to receive(:execute).and_call_original

        put "/api/v1/tickets/#{ticket.id}/update_customer",
            params: { customer_id: customer.id, organization_id: organization.id },
            as:     :json

        expect(Service::Ticket::ForcedUpdate)
          .to have_received(:execute).with(ticket, { 'customer_id' => customer.id, 'organization_id' => organization.id }, current_user: agent)
      end

      it 'uses ForcedUpdate service with customer only' do
        allow(Service::Ticket::ForcedUpdate).to receive(:execute).and_call_original

        put "/api/v1/tickets/#{ticket.id}/update_customer",
            params: { customer_id: customer.id, not_permited: :field },
            as:     :json

        expect(Service::Ticket::ForcedUpdate)
          .to have_received(:execute).with(ticket, { 'customer_id' => customer.id }, current_user: agent)
      end
    end

    context 'with a customer', authenticated_as: -> { ticket.customer } do
      it 'access is forbidden' do
        put "/api/v1/tickets/#{ticket.id}/update_customer", params: { title: }
        expect(response).to have_http_status(:forbidden)
      end
    end
  end

  describe 'performs requested macro changes after updating the ticket (#5866)' do
    let(:ticket)   { create(:ticket) }
    let(:agent)    { create(:agent, groups: [ticket.group]) }
    let(:title)    { 'Updated title' }
    let(:state)    { Ticket::State.lookup(name: 'closed') }
    let(:priority) { Ticket::Priority.lookup(name: '3 high') }
    let(:macro)    { create(:macro, perform:) }

    let(:perform) do
      {
        'ticket.state_id'    => { 'value' => state.id },
        'ticket.priority_id' => { 'value' => priority.id },
      }
    end

    let(:params) do
      {
        'title'                 => title,
        'macro.id'              => macro.id,
        'macro.perform_changes' => ['ticket.state_id'],
      }
    end

    context 'with an agent', authenticated_as: :agent do
      it 'performs just the requested macro changes' do
        expect { put "/api/v1/tickets/#{ticket.id}", params:, as: :json }
          .to change { ticket.reload.title }.to(title)
          .and change { ticket.reload.state }.to(state)
          .and not_change { ticket.reload.priority }
      end
    end

    context 'with a customer', authenticated_as: -> { ticket.customer } do
      it 'does not perform requested macro changes' do
        expect { put "/api/v1/tickets/#{ticket.id}", params:, as: :json }
          .to change { ticket.reload.title }
          .and not_change { ticket.reload.state }
          .and not_change { ticket.reload.priority }
      end
    end
  end

  describe 'performs the checklist macro action requested by the legacy ticket view', current_user_id: 1 do
    let(:ticket)   { create(:ticket) }
    let(:agent)    { create(:agent, groups: [ticket.group]) }
    let(:template) { create(:checklist_template, items: ['Template item 1', 'Template item 2']) }
    let(:macro)    { create(:macro, perform: { 'checklist.add_from_template' => { 'checklist_template_id' => template.id.to_s } }) }

    let(:params) do
      {
        'title'                 => 'Updated title',
        'macro.id'              => macro.id,
        'macro.perform_changes' => ['checklist.add_from_template'],
      }
    end

    context 'with an agent', authenticated_as: :agent do
      it 'adds the checklist from the template', :aggregate_failures do
        put "/api/v1/tickets/#{ticket.id}", params:, as: :json

        expect(response).to have_http_status(:ok)
        expect(ticket.reload.title).to eq('Updated title')
        expect(ticket.checklist.sorted_items.map(&:text)).to eq(['Template item 1', 'Template item 2'])
      end
    end
  end

  describe 'group with no email address configured' do
    let(:group)  { create(:group, email_address: nil) }
    let(:agent)  { create(:agent, groups: [group]) }
    let(:ticket) { create(:ticket, group: group) }

    context 'POST /api/v1/ticket_articles', authenticated_as: -> { agent } do
      it 'returns an unprocessable content error with a descriptive message' do
        post '/api/v1/ticket_articles',
             params: { ticket_id: ticket.id, body: 'some body', type: 'email', to: 'customer@example.com' },
             as:     :json

        expect(response).to have_http_status(:unprocessable_content)
        expect(json_response['error']).to eq('This group has no email address configured for outgoing communication.')
      end
    end

    context 'POST /api/v1/tickets', authenticated_as: -> { agent } do
      it 'returns an unprocessable content error with a descriptive message' do
        post '/api/v1/tickets',
             params: {
               title:    'a ticket',
               group:    group.name,
               article:  { body: 'some body', type: 'email', to: 'customer@example.com' },
               customer: agent.email,
             },
             as:     :json

        expect(response).to have_http_status(:unprocessable_content)
        expect(json_response['error']).to eq('This group has no email address configured for outgoing communication.')
      end
    end
  end
end
