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

require 'rails_helper'

RSpec.describe Service::User::Signup, performs_jobs: true do
  subject(:service_result) { described_class.execute(user_data:, resend:) }

  let(:resend) { false }

  let(:user_data) do
    {
      email:     'bender@futurama.fiction',
      firstname: 'Bender',
      lastname:  'Rodríguez',
      password:  'IloveBender1337'
    }
  end

  shared_examples 'raising an error' do |klass, message, message_placeholder: nil|
    if message_placeholder
      it 'raises an error', :aggregate_failures do
        expect { service_result }.to raise_error do |error|
          expect(error).to be_a(klass)
            .and have_attributes(
              message:  include(message),
              metadata: [include(message), *message_placeholder],
            )
        end
      end
    else
      it 'raises an error' do
        expect { service_result }.to raise_error(klass, include(message))
      end
    end
  end

  shared_examples 'returning success' do |with_new_user: false, with_existing_user: false, with_resend: false|
    it 'returns success' do
      expect(service_result).to be(true)
    end

    it 'creates an unverified user account', if: with_new_user do
      service_result
      expect(User.find_by(email: 'bender@futurama.fiction')).to be_present.and have_attributes(verified: false)
    end

    it 'defers the delivery to a background job', if: with_new_user || (with_existing_user != with_resend) do
      expect { service_result }.to have_enqueued_job(NotificationMailerJob)
    end

    it 'does not enqueue a delivery', if: !with_new_user && with_existing_user && with_resend do
      expect { service_result }.not_to have_enqueued_job(NotificationMailerJob)
    end

    it 'does not deliver an email within the request' do
      allow(NotificationFactory::Mailer).to receive(:deliver)

      service_result

      expect(NotificationFactory::Mailer).not_to have_received(:deliver)
    end

    it 'sends an email with the verification link', if: with_new_user || (!with_existing_user && with_resend) do
      message = nil

      allow(NotificationFactory::Mailer).to receive(:deliver) do |params|
        message = params[:body]
      end

      perform_enqueued_jobs { service_result }

      expect(message).to include("<a href=\"http://zammad.example.com/desktop/signup/verify/#{Token.last[:token]}\">")
    end

    it 'sends an email with the password reset link', if: with_existing_user && !with_resend do
      message = nil

      allow(NotificationFactory::Mailer).to receive(:deliver) do |params|
        message = params[:body]
      end

      perform_enqueued_jobs { service_result }

      expect(message).to include("<a href=\"http://zammad.example.com/desktop/reset-password/verify/#{Token.last[:token]}\">")
    end

    it 'creates no token', if: !with_new_user && with_existing_user && with_resend do
      expect { service_result }.not_to change(Token, :count)
    end

    it 'sends no email', if: !with_new_user && with_existing_user && with_resend do
      message = nil

      allow(NotificationFactory::Mailer).to receive(:deliver) do |params|
        message = params[:body]
      end

      perform_enqueued_jobs { service_result }

      expect(message).to be_nil
    end

  end

  shared_examples 'holding the response deadline' do
    it 'holds the response until the deadline' do
      started = Process.clock_gettime(Process::CLOCK_MONOTONIC)

      service_result

      elapsed = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).seconds

      expect(elapsed).to be >= Service::Concerns::HoldsResponseDeadline::RESPONSE_DEADLINE
    end
  end

  shared_examples 'raising error if import mode is on' do
    context 'when in import mode' do
      before { Setting.set('import_mode', true) }

      it 'raises an error' do
        expect { service_result }
          .to raise_error(Exceptions::UnprocessableContent, message)
      end

      it 'adds message to the log' do
        allow(Rails.logger).to receive(:error)

        service_result rescue nil # rubocop:disable Style/RescueModifier

        expect(Rails.logger)
          .to have_received(:error)
          .with(message)
      end
    end
  end

  # The tolerance covers scheduler jitter only; both calls are held to the same deadline.
  def expect_indistinguishable(first, second)
    durations = [first, second].map do |email|
      started = Process.clock_gettime(Process::CLOCK_MONOTONIC)

      described_class.execute(user_data: { email: }, resend: true)

      (Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).seconds
    end

    expect((durations.first - durations.last).abs)
      .to be < (Service::Concerns::HoldsResponseDeadline::RESPONSE_DEADLINE / 10)
  end

  describe '#execute' do
    context 'with disabled user signup' do
      before do
        Setting.set('user_create_account', false)
      end

      it_behaves_like 'raising an error', Service::CheckFeatureEnabled::FeatureDisabledError, 'This feature is not enabled.'
    end

    context 'with valid user data' do
      it_behaves_like 'returning success', with_new_user: true

      it_behaves_like 'raising error if import mode is on' do
        let(:message) { 'Could not create user and send verification email because import_mode setting is on.' }
      end
    end

    context 'with additional user data' do
      let(:organization) { create(:organization) }
      let(:user_data) do
        {
          email:            'bender@futurama.fiction',
          firstname:        'Bender',
          lastname:         'Rodriguez',
          password:         'IloveBender1337',
          login:            'fry@futurama.fiction',
          verified:         true,
          organization_id:  organization.id,
          organization_ids: [organization.id],
        }
      end

      it 'assigns only the permitted attributes', :aggregate_failures do
        service_result

        user = User.find_by(email: 'bender@futurama.fiction')

        expect(user).to have_attributes(
          firstname:    'Bender',
          lastname:     'Rodriguez',
          login:        'bender@futurama.fiction',
          verified:     false,
          organization: nil,
        )
        expect(user.organizations).to be_empty
      end
    end

    context 'with invalid user data' do
      let(:password) { 'IloveBender1337' }
      let(:user_data) do
        {
          email:     'bender@futurama.fiction',
          firstname: 'Bender',
          lastname:  'Rodríguez',
          password:  password
        }
      end

      context 'when the password is weak' do
        let(:password) { 'idonotlovebenderandthisiswrong' }

        it_behaves_like 'raising an error', PasswordPolicy::Error, 'Invalid password'
      end

      context 'when the password is too short' do
        let(:password) { 'brBR2999' }

        it_behaves_like 'raising an error', PasswordPolicy::Error, 'Invalid password', message_placeholder: [10]
      end

      context 'when the email is already taken' do
        before do
          create(:user, email: 'bender@futurama.fiction')
        end

        it_behaves_like 'returning success', with_existing_user: true
      end

      it_behaves_like 'raising error if import mode is on' do
        let(:message) { 'Could not create user and send verification email because import_mode setting is on.' }
      end
    end

    context 'when resending verification email' do
      let(:resend)   { true }
      let(:verified) { false }
      let(:active)   { true }

      before do
        create(:user, email: 'bender@futurama.fiction', verified: verified, active: active)
      end

      it_behaves_like 'returning success', with_resend: true
      it_behaves_like 'holding the response deadline'

      it 'takes the same time for a known and an unknown email address' do
        expect_indistinguishable('bender@futurama.fiction', 'leela@futurama.fiction')
      end

      context 'when user is already verified' do
        let(:verified) { true }

        it_behaves_like 'returning success', with_existing_user: true, with_resend: true
        it_behaves_like 'holding the response deadline'
      end

      context 'when no account exists for the email address' do
        let(:user_data) { { email: 'leela@futurama.fiction' } }

        it_behaves_like 'holding the response deadline'
      end

      context 'when user is inactive' do
        let(:active) { false }

        it_behaves_like 'returning success', with_existing_user: true, with_resend: true
        it_behaves_like 'holding the response deadline'
      end

      it_behaves_like 'raising error if import mode is on' do
        let(:message) { 'Could not send user verification email because import_mode setting is on.' }
      end
    end
  end
end
