module Teams
  class StaffAssignmentError < StandardError
    attr_reader :message

    def initialize(message)
      @message = message
      super(message)
    end
  end

  class StaffAssignment
    def self.call(team:, user:, staff_kind: "transmission", membership: nil)
      new(team: team, user: user, staff_kind: staff_kind, membership: membership).call
    end

    def initialize(team:, user:, staff_kind: "transmission", membership: nil)
      @team = team
      @user = user
      @staff_kind = "transmission"
      @membership = membership
    end

    def call
      StaffEmailValidator.assert_available!(
        team: @team, email: @user.email, except_user: @user
      )

      ut = @membership || @user.user_teams.find_by!(team: @team)
      return ut if ut.staff_kind == "transmission"

      Entitlements.new(@team).assert_can_invite!
      ut.update!(staff_kind: "transmission")
      ut
    end
  end

  class StaffEmailValidator
    def self.assert_available!(team:, email:, except_user: nil, staff_kind: nil)
      new(team: team, email: email, except_user: except_user).assert_available!
    end

    def initialize(team:, email:, except_user: nil)
      @team = team
      @email = email.to_s.downcase.strip
      @except_user = except_user
    end

    def assert_available!
      user_scope = @team.user_teams.joins(:user).where(users: { email: @email }).where.not(staff_kind: nil)
      user_scope = user_scope.where.not(user_id: @except_user.id) if @except_user
      if user_scope.exists?
        raise StaffAssignmentError,
              "L'email #{@email} è già assegnata come responsabile trasmissione per questa squadra."
      end

      inv = @team.team_invitations.pending.where("LOWER(email) = ?", @email)
      return unless inv.exists?

      raise StaffAssignmentError,
            "Esiste già un invito in sospeso per #{@email}."
    end
  end
end
