# frozen_string_literal: true

require 'rails_helper'

RSpec.describe User do
  it_behaves_like 'uuidable'
  it_behaves_like 'directionable'

  it { is_expected.to belong_to :account }
  it { is_expected.to belong_to(:language).optional }
  it { is_expected.to have_one :cart }
  it { is_expected.to have_many :orders }
  it { is_expected.to have_many :comments }

  it { is_expected.to validate_presence_of :name }
  it { is_expected.to validate_presence_of :role }
  it { is_expected.to validate_presence_of :email }

  it { should define_enum_for(:role).with_values(%i[customer admin manager]) }

  describe '.generate_from_email' do
    let(:user) { create(:user) }
    let(:account) { user.account }
    let(:email) { user.email }

    subject { described_class.generate_from_email(email, account) }

    context 'when email belongs to a user' do
      it { is_expected.to eql user }
      it { expect(subject.autogenerated).to be false }
      it { expect(subject.account).to eql account }
    end

    context 'when email is new' do
      let(:email) { 'brand@new.email' }

      it { expect(subject.valid?).to be true }
      it { expect(subject.email).to eql email }
      it { expect(subject.name).to eql email }
      it { expect(subject.role).to eql 'customer' }
      it { expect(subject.autogenerated).to be true }
      it { expect(subject.account).to eql account }
    end

    context 'when email belongs to another account' do
      let!(:other_user) { create(:user) }
      let(:email) { other_user.email }

      it { expect(subject.valid?).to be true }
      it { expect(subject.email).to eql email }
      it { expect(subject.name).to eql email }
      it { expect(subject.role).to eql 'customer' }
      it { expect(subject.autogenerated).to be true }
      it { expect(subject.account).to eql account }
    end
  end
end
