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

require 'rails_helper'

RSpec.describe Service::Ticket::Create, current_user_id: -> { user.id } do
  subject(:service_result) { described_class.with_current_user(user).execute(ticket_data:) }

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

  describe '#execute' do
    let(:sample_title) { Faker::Lorem.sentence }

    let(:ticket_data) do
      {
        title:    sample_title,
        group:    group,
        customer: customer
      }
    end

    it 'creates a ticket with given metadata' do
      expect(service_result)
        .to have_attributes(
          title:    sample_title,
          group:    group,
          customer: customer
        )
    end

    it 'creates a ticket with customer email address' do
      test_email = Faker::Internet.unique.email
      ticket_data[:customer] = { email: test_email }

      expect(service_result.customer).to have_attributes(
        email:    test_email,
        role_ids: Role.signup_role_ids
      )
    end

    it 'takes an existing customer by email address' do
      ticket_data[:customer] = { email: customer.email }

      expect(service_result.customer).to eq(customer)
    end

    context 'when the customer is given as a phone number' do
      let(:phone_number) { '+49 30 609812345' }

      before { ticket_data[:customer] = { phone: phone_number } }

      it 'creates a customer with the number' do
        expect(service_result.customer).to have_attributes(
          phone:    phone_number,
          email:    '',
          role_ids: Role.signup_role_ids
        )
      end

      it 'indexes the number as the caller ID of the new customer, so the next call finds them' do
        expect(Cti::CallerId.where(user_id: service_result.customer.id, level: 'known').pluck(:caller_id))
          .to include('4930609812345')
      end

      it 'takes an existing customer whose phone is the number, however written' do
        existing_customer = create(:customer, phone: '030 / 609812345')

        expect(service_result.customer).to eq(existing_customer)
      end

      it 'takes an existing customer whose mobile is the number' do
        existing_customer = create(:customer, mobile: '0049 30 609812345')

        expect(service_result.customer).to eq(existing_customer)
      end

      it 'passes over a user who only mentions the number' do
        create(:customer, note: "Reachable at #{phone_number} in the morning.")

        expect(service_result.customer).to have_attributes(phone: phone_number, note: '')
      end

      it 'rejects a value that is no phone number' do
        ticket_data[:customer] = { phone: 'not a number' }

        expect { service_result }.to raise_error(Exceptions::InvalidAttribute, 'The phone number is invalid.')
      end

      it 'rejects a number too short to be one' do
        ticket_data[:customer] = { phone: '12345' }

        expect { service_result }.to raise_error(Exceptions::InvalidAttribute)
      end
    end

    it 'fails to create ticket without access' do
      allow_any_instance_of(TicketPolicy)
        .to receive(:create?).and_return(false)

      expect { service_result }
        .to raise_error(Pundit::NotAuthorizedError)
    end

    it 'adds article when present' do
      sample_body = Faker::Lorem.sentence
      ticket_data[:article] = {
        body: sample_body
      }

      expect(service_result.articles.first)
        .to have_attributes(
          body: sample_body
        )
    end

    context 'when an article is present' do
      before do
        ticket_data[:article] = { body: Faker::Lorem.sentence }
      end

      it 'runs the core workflow validation only for the ticket data', :aggregate_failures do
        allow(CoreWorkflow).to receive(:perform).and_call_original

        expect(service_result.screen).to eq('create_middle')
        expect(CoreWorkflow).to have_received(:perform)
          .with(hash_including(payload: hash_including('request_id' => 'ChecksCoreWorkflow.validate_workflows')))
          .once
      end

      context 'when a value of the ticket is not allowed' do
        let(:open_state) { Ticket::State.find_by(name: 'open') }

        before do
          ticket_data[:state] = open_state
          create(:core_workflow,
                 object:  'Ticket',
                 perform: {
                   'ticket.state_id': {
                     operator:      'remove_option',
                     remove_option: [open_state.id.to_s]
                   },
                 })
        end

        it 'raises an error and creates no ticket' do
          expect { service_result }
            .to raise_error(Exceptions::ApplicationModel, "Invalid value '#{open_state.id}' for field 'state_id'!")
            .and not_change(Ticket, :count)
        end
      end
    end

    it 'fills in the sender and the recipient of an agent\'s article, but keeps those of a prepared one', :aggregate_failures do
      ticket_data[:article] = { body: 'Hello', type: 'phone', sender: 'Agent', to: 'someone@example.com' }

      expect(service_result.articles.first.to).not_to eq('someone@example.com')

      prepared = described_class.with_current_user(user).execute(ticket_data: ticket_data.merge(article: { body: 'Hello', type: 'phone', sender: 'Agent', to: 'someone@example.com' }), prepared_article: true)
      expect(prepared.articles.first.to).to eq('someone@example.com')
    end

    context 'when email article should be created, but to is not present' do
      let(:customer) { create(:customer, email: '') }

      let(:ticket_data) do
        {
          title:    sample_title,
          group:    group,
          customer: customer,
          article:  {
            body: Faker::Lorem.sentence,
            type: 'email',
            to:   nil,
          }
        }
      end

      it 'raises an error' do
        expect { service_result }.to raise_error(Exceptions::InvalidAttribute, 'Sending an email without a valid recipient is not possible.')
      end
    end

    context 'when email article should be created, but to is not a valid email' do
      let(:customer) { create(:customer) }

      let(:ticket_data) do
        {
          title:    sample_title,
          group:    group,
          customer: customer,
          article:  {
            body: Faker::Lorem.sentence,
            type: 'email',
            to:   'invalid-email',
          }
        }
      end

      it 'raises an error' do
        expect { service_result }.to raise_error(Exceptions::InvalidAttribute, 'Sending an email without a valid recipient is not possible.')
      end
    end

    it 'adds tags when present' do
      sample_tags = [Faker::Lorem.word]

      ticket_data[:tags] = sample_tags

      expect(service_result.tag_list)
        .to eq sample_tags
    end

    context 'when adding links' do
      context 'when linking to a ticket' do
        let(:other_ticket) { create(:ticket, customer: customer) }
        let(:links) do
          [
            { link_object: other_ticket, link_type: 'child' },
            { link_object: other_ticket, link_type: 'normal' },
          ]
        end
        let(:ticket_data) { super().merge(links:) }

        context 'when user has agent access to the other ticket' do
          before do
            user.groups << other_ticket.group
          end

          it 'adds links correctly' do
            expect(Link.list(link_object: 'Ticket', link_object_value: service_result.id)).to contain_exactly(
              { 'link_object' => 'Ticket', 'link_object_value' => other_ticket.id, 'link_type' => 'parent' },
              { 'link_object' => 'Ticket', 'link_object_value' => other_ticket.id, 'link_type' => 'normal' },
            )
          end
        end

        context 'when user has no agent access to the other ticket' do
          it 'raises an error' do
            expect { service_result }
              .to raise_error(Pundit::NotAuthorizedError)
          end
        end

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

          it 'raises an error' do
            expect { service_result }
              .to raise_error(Pundit::NotAuthorizedError)
          end
        end
      end

      context 'when linking to a KB answer' do
        include_context 'basic Knowledge Base'

        let(:translation) { internal_answer.translations.first }
        let(:links) do
          [
            { link_object: translation, link_type: 'normal' },
          ]
        end
        let(:ticket_data) { super().merge(links:) }

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

          it 'raises an error' do
            expect { service_result }
              .to raise_error(Pundit::NotAuthorizedError)
          end
        end

        context 'when the user reader access to the KB answer' do
          it 'creates the ticket with the link' do
            expect(Link.list(link_object: 'Ticket', link_object_value: service_result.id))
              .to contain_exactly(
                {
                  'link_object'       => 'KnowledgeBase::Answer::Translation',
                  'link_object_value' => translation.id,
                  'link_type'         => 'normal'
                },
              )
          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(:user)           { create(:agent, groups: [group], roles: [kb_editor_role]) }

          it 'creates the ticket with the link' do
            expect(Link.list(link_object: 'Ticket', link_object_value: service_result.id))
              .to contain_exactly(
                {
                  'link_object'       => 'KnowledgeBase::Answer::Translation',
                  'link_object_value' => translation.id,
                  'link_type'         => 'normal'
                },
              )
          end
        end
      end
    end

    context 'when tag creation is disabled' do
      before do
        Setting.set('tag_new', false)
      end

      it 'does not adds tags when present' do
        sample_tags = [Faker::Lorem.word]

        ticket_data[:tags] = sample_tags

        expect(service_result.tag_list).to be_empty
      end
    end

    describe 'shared draft handling' do
      let(:shared_draft) { create(:ticket_shared_draft_start, group:) }

      before { ticket_data[:shared_draft] = shared_draft }

      it 'destroys given shared draft' do
        service_result

        expect(Ticket::SharedDraftStart).not_to exist(shared_draft.id)
      end

      it 'raises error if shared drafts are disabled on that group' do
        group.update! shared_drafts: false

        expect { service_result }
          .to raise_error(Exceptions::UnprocessableContent)
      end

      it 'raises error if shared draft group does not match ticket group' do
        shared_draft.update! group: create(:group, shared_drafts: true)

        expect { service_result }
          .to raise_error(Exceptions::UnprocessableContent)
      end

      # A user who may not create the ticket never reaches the draft: the
      #   transaction rolls the destroy back. Only a customer, who may create a
      #   ticket in any group, can consume a draft they have no access to.
      context 'when the user has no create access to the shared draft group' do
        let(:user) { create(:customer) }

        before { ticket_data[:customer] = user }

        it 'raises error' do
          expect { service_result }
            .to raise_error(Pundit::NotAuthorizedError)
        end

        it 'does not destroy given shared draft' do
          suppress(Pundit::NotAuthorizedError) { service_result }

          expect(Ticket::SharedDraftStart).to exist(shared_draft.id)
        end
      end
    end

    describe 'issue trackers handling' do
      let(:gitlab_link) { 'https://git.example.com/issue/123' }
      let(:github_link) { 'https://github.com/issue/123' }

      before do
        ticket_data[:external_references] = {
          gitlab: [gitlab_link],
          github: [github_link],
          idoit:  [42],
        }
      end

      context 'when none enabled' do
        it 'adds no data' do
          expect(service_result.preferences).to be_blank
        end
      end

      context 'when gitlab is enabled' do
        before do
          Setting.set('gitlab_integration', true)
        end

        it 'adds gitlab links' do
          expect(service_result.preferences).to eq({ 'gitlab' => { 'issue_links' => [gitlab_link] } })
        end
      end

      context 'when github is enabled' do
        before do
          Setting.set('github_integration', true)
        end

        it 'adds github links' do
          expect(service_result.preferences).to eq({ 'github' => { 'issue_links' => [github_link] } })
        end
      end

      context 'when idoit is enabled' do
        before do
          Setting.set('idoit_integration', true)
        end

        it 'adds idoit object ids' do
          expect(service_result.preferences).to eq({ 'idoit' => { 'object_ids' => [42] } })
        end
      end
    end
  end
end
